
/****** Object:  StoredProcedure [dbo].[usp_130_Comparison_Table]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_130_Comparison_Table]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

CREATE PROCEDURE [dbo].[usp_130_Comparison_Table] ( @Err INT OUTPUT )
AS --******************************
-- RapidReconciler A113 Build Comparison Table
--******************************
    DECLARE @@Step VARCHAR(30), @@Process VARCHAR(100), @rowc INT, @Company VarChar(5)
    SET @@Step = ''130 Comparison Table''

-- Preparing table
    SET @@Process = ''Truncating Comparison Table ...''
    EXEC Update_Server_Log @@Step, @@Process

	TRUNCATE TABLE	RCardexLedgerCompare

--Add Posted Cardex Records to comparison table.
    SET @@Process = ''Inserting posted cardex records no Work Orders ...''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO dbo.RCardexLedgerCompare
            SELECT  CX.ILKCO, CX.InventoryAccount, ''No GL'', CX.ILDCTO, CX.ILDCT, CX.ILDOC, CX.PeriodEnds,
					0, SUM(CX.ILPAID), 0,0,0,'''','''', Min(ILTRDJ)
            FROM    dbo.F4111B CX With (NOLOCK)
	        WHERE   ILDGL > ''1901-01-01 00:00:00.000'' And ILDCT Not In (''IC'',''IM'', ''LC'',''LM'')
            GROUP BY CX.ILKCO, CX.InventoryAccount, CX.PeriodEnds, CX.ILDCT, CX.ILDOC, CX.ILDCTO



		--Transaction logging		
			SELECT  @err = @@error, @rowc = @@rowcount
			EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
			IF @err <> 0 BEGIN GOTO Err_Handler END

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS


-- Work Orders are separate so the batch number can be grouped and added to the table
    SET @@Process = ''Inserting posted cardex records Work Orders ...''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO dbo.RCardexLedgerCompare
            SELECT  CX.ILKCO, CX.InventoryAccount, ''No GL'', CX.ILDCTO, CX.ILDCT, CX.ILDOC, CX.PeriodEnds,
					ILICU, SUM(CX.ILPAID), 0,0,0,'''','''', Min(ILTRDJ)
            FROM    dbo.F4111B CX With (NOLOCK)
		    WHERE   ILDGL > ''1901-01-01 00:00:00.000'' And ILDCT In (''IC'',''IM'', ''LC'',''LM'')
            GROUP BY CX.ILKCO, CX.InventoryAccount, CX.PeriodEnds, CX.ILDCT, CX.ILDOC, CX.ILDCTO, ILICU

		--Transaction logging		
			SELECT  @err = @@error, @rowc = @@rowcount
			EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
			IF @err <> 0 BEGIN GOTO Err_Handler END

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS



--Add UnPosted Cardex Records to comparison table.
    SET @@Process = ''Inserting unposted cardex records ...''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO dbo.RCardexLedgerCompare
            SELECT  CX.ILKCO, CX.InventoryAccount, 
					Case When ILDCT In (''IC'',''IM'',''LC'',''LM'') Then ''Mfg Accounting Required''	Else ''Sales Update Required'' End, 
					CX.ILDCTO, CX.ILDCT, CX.ILDOC, CX.PeriodEnds, 0, SUM(CX.ILPAID),0,0,0,'''','''', Min(ILTRDJ)
            FROM    dbo.F4111B CX With (NOLOCK)
	        WHERE   ILDGL In (''1900-01-01 00:00:00.000'', ''1901-01-01 00:00:00.000'')
            GROUP BY CX.ILKCO, CX.InventoryAccount, CX.PeriodEnds, CX.ILDCT, CX.ILDOC, CX.ILDCTO

		--Transaction logging		
			SELECT  @err = @@error, @rowc = @@rowcount
			EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
			IF @err <> 0 BEGIN GOTO Err_Handler END

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS

-- Cardex complete
    SET @@Process = ''Cardex records complete ...''
    EXEC Update_Server_Log @@Step, @@Process









--Add GL Data
--Update Matching GL Amounts - No Work Orders
    DECLARE C1 CURSOR FOR 
	Select	 CompanyNumber
	From	 RCompanies
	Order By CompanyNumber

    OPEN C1
    FETCH NEXT FROM C1 INTO @Company
    WHILE 		@@FETCH_STATUS = 0
    BEGIN

    SET @@Process = ''Matching GL, no work orders '' + @Company
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare
    SET     Status = '' '', LedgerAmount = T.GLAA, CardexLedgerVariance = T.GLAA - CardexAmount
    FROM    RCardexLedgerCompare CXGL,
            ( SELECT    GLCO, GLANI, PeriodEnds,GLDCT, GLDOC, GLDCTO, SUM(GLAA) AS GLAA
              FROM      dbo.F0911
              WHERE     GLDCT NOT IN ( ''IC'', ''IM'', ''LC'',''LM'' )
              GROUP BY  GLCO, GLANI, PeriodEnds, GLDCT, GLDOC, GLDCTO ) AS T
    WHERE   CXGL.CompanyNumber = @Company And
			CXGL.CompanyNumber = T.GLCO AND CXGL.InventoryAccount = T.GLANI AND
            CXGL.PeriodEnds = T.PeriodEnds AND CXGL.DocType = T.GLDCT AND
            CXGL.DocNumber = T.GLDOC AND CXGL.OrderType = T.GLDCTO

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0  GOTO Err_Handler


            FETCH NEXT FROM C1 INTO @Company
    END

    CLOSE C1
    DEALLOCATE C1

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS



--Update Matching GL Amounts - Work Orders by SubLedger
If Exists (Select * From RCompanies Where SubledgerWO = 1)
Begin
    DECLARE C1 CURSOR FOR 
	Select	 CompanyNumber
	From	 RCompanies
	Order By CompanyNumber

    OPEN C1
    FETCH NEXT FROM C1 INTO @Company
    WHILE 		@@FETCH_STATUS = 0
    BEGIN

    SET @@Process = ''Updating matching GL, work orders by sub-ledger '' + @Company
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare
    SET     Status = '' '', LedgerAmount = T.GLAA, CardexLedgerVariance = T.GLAA - CardexAmount
    FROM    RCardexLedgerCompare CXGL, RCompanies C,
            ( SELECT    GLCO, GLANI, PeriodEnds, GLDCT, GLSBL, GLDCTO, GLICU, SUM(GLAA) AS GLAA
              FROM      dbo.F0911
              WHERE     GLDCT IN ( ''IC'', ''IM'', ''LC'',''LM'' )
              GROUP BY  GLCO, GLANI, PeriodEnds, GLDCT, GLSBL, GLDCTO, GLICU) AS T
    WHERE   CXGL.CompanyNumber = @Company And
			CXGL.CompanyNumber = T.GLCO AND
            CXGL.InventoryAccount = T.GLANI AND
            CXGL.PeriodEnds = T.PeriodEnds AND
            CXGL.DocType = T.GLDCT AND
            CXGL.DocNumber = T.GLSBL AND
            CXGL.OrderType = T.GLDCTO AND
            CXGL.MfgBatch = T.GLICU AND
            CXGL.CompanyNumber = C.CompanyNumber AND
            SubledgerWO = 1

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0  GOTO Err_Handler


            FETCH NEXT FROM C1 INTO @Company
    END

    CLOSE C1
    DEALLOCATE C1

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
End



--Update Matching GL Amounts - Work Orders by Document
If Exists (Select * From RCompanies Where SubledgerWO = 0)
Begin
    DECLARE C1 CURSOR FOR 
	Select	 CompanyNumber
	From	 RCompanies
	Order By CompanyNumber

    OPEN C1
    FETCH NEXT FROM C1 INTO @Company
    WHILE 		@@FETCH_STATUS = 0
    BEGIN

    SET @@Process = ''Updating matching GL, work orders by document '' + @Company
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare
    SET     Status = '' '', LedgerAmount = T.GLAA,CardexLedgerVariance = T.GLAA - CardexAmount
    FROM    RCardexLedgerCompare CXGL,
            RCompanies C,
            ( SELECT    GLCO, GLANI, PeriodEnds, GLDCT, GLDOC, GLDCTO, GLICU, SUM(GLAA) AS GLAA
              FROM      dbo.F0911
              WHERE     GLDCT IN ( ''IC'', ''IM'', ''LC'',''LM'' )
              GROUP BY  GLCO, GLANI, PeriodEnds, GLDCT, GLDOC, GLDCTO, GLICU ) AS T
    WHERE   CXGL.CompanyNumber = @Company And
			CXGL.CompanyNumber = T.GLCO AND CXGL.InventoryAccount = T.GLANI AND
            CXGL.PeriodEnds = T.PeriodEnds AND CXGL.DocType = T.GLDCT AND
            CXGL.DocNumber = T.GLDOC AND CXGL.OrderType = T.GLDCTO AND
            CXGL.MfgBatch = T.GLICU AND  CXGL.CompanyNumber = C.CompanyNumber AND
            SubledgerWO = 0

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0  GOTO Err_Handler


            FETCH NEXT FROM C1 INTO @Company
    END

    CLOSE C1
    DEALLOCATE C1

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
End
















-- Add GL with no cardex, no work orders
    SET @@Process = ''Adding GL without cardex, no work orders''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO dbo.RCardexLedgerCompare
            SELECT  F.GLCO, F.GLANI, ''No Cardex'', F.GLDCTO, F.GLDCT, F.GLDOC, F.PeriodEnds,
                    0, 0, SUM(F.GLAA), Sum(F.GLAA), 0, '''', '''', Min(GLDGJ)
            FROM    dbo.F0911 F
		    WHERE   F.GLDCT NOT IN ( ''IC'', ''IM'', ''LC'', ''LM'' ) AND
                    NOT EXISTS ( SELECT *
                                 FROM   RCardexLedgerCompare CX
                                 WHERE  F.GLCO = CX.CompanyNumber AND F.GLANI = CX.InventoryAccount AND
                                        F.PeriodEnds = CX.PeriodEnds AND F.GLDCT = CX.DocType AND
                                        F.GLDOC = CX.DocNumber AND F.GLDCTO = CX.OrderType )
            GROUP BY F.GLCO, F.GLANI, F.PeriodEnds, F.GLDCT, F.GLDOC, F.GLDCTO

		--Transaction logging		
			SELECT  @err = @@error, @rowc = @@rowcount
			EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
			IF @err <> 0 BEGIN GOTO Err_Handler END

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS






-- Add GL with no cardex, work orders by subledger
Set @rowc = (Select Count(*) From RCompanies Where SubledgerWO = 1)
If @rowc > 0
Begin
    SET @@Process = ''Adding GL without cardex, work orders by subledger''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO dbo.RCardexLedgerCompare
            SELECT  F.GLCO, F.GLANI,''No Cardex'', F.GLDCTO, F.GLDCT, F.GLSBL, F.PeriodEnds, F.GLICU,
                    0, SUM(F.GLAA), SUM(F.GLAA), 0, '''', '''', Min(GLDGJ)
            FROM    dbo.F0911 F 
		    INNER JOIN RCompanies ON ( CompanyNumber = GLCO AND SubledgerWO = 1) 
            WHERE   F.GLDCT IN ( ''IC'', ''IM'', ''LC'',''LM'' ) AND
					Not Exists (Select * From RCardexLedgerCompare CX Where
						F.GLCO = CX.CompanyNumber AND  F.GLANI = CX.InventoryAccount AND
                        F.PeriodEnds = CX.PeriodEnds AND F.GLDCT = CX.DocType AND
                        F.GLSBL = CX.DocNumber AND F.GLDCTO = CX.OrderType AND
                        F.GLICU = CX.MfgBatch )
            GROUP BY F.GLCO, F.GLANI, F.PeriodEnds, F.GLDCT, F.GLSBL, F.GLDCTO, F.GLICU

		--Transaction logging		
			SELECT  @err = @@error, @rowc = @@rowcount
			EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
			IF @err <> 0 BEGIN GOTO Err_Handler END

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
End





-- Add GL with no cardex, work orders by document or batch
Set @rowc = (Select Count(*) From RCompanies Where SubledgerWO In (0,2))
If @rowc > 0
Begin
    SET @@Process = ''GL without cardex, work orders by document or batch''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO dbo.RCardexLedgerCompare
            SELECT  F.GLCO, F.GLANI, ''No Cardex'', F.GLDCTO, F.GLDCT, F.GLDOC, F.PeriodEnds, F.GLICU,
                    0, SUM(F.GLAA), SUM(F.GLAA), 0, '''', '''', Min(GLDGJ)
            FROM    dbo.F0911 F 
			INNER JOIN RCompanies ON ( CompanyNumber = GLCO )
            WHERE   F.GLDCT IN ( ''IC'', ''IM'', ''LC'',''LM'' ) AND
                    NOT EXISTS ( SELECT *
                                 FROM   RCardexLedgerCompare CX
                                 WHERE  F.GLCO = CX.CompanyNumber AND F.GLANI = CX.InventoryAccount AND
                                        F.PeriodEnds = CX.PeriodEnds AND F.GLDCT = CX.DocType AND
                                        F.GLDOC = CX.DocNumber AND F.GLDCTO = CX.OrderType AND
                                        F.GLICU = CX.MfgBatch ) AND
                    SubLedgerWO IN ( 0, 2 )
            GROUP BY F.GLCO, F.GLANI, F.PeriodEnds, F.GLDCT, F.GLDOC, F.GLDCTO, F.GLICU

		--Transaction logging		
			SELECT  @err = @@error, @rowc = @@rowcount
			EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
			IF @err <> 0 BEGIN GOTO Err_Handler END

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS

End







--Calculate Variance
			SET @@Process = ''Calculating Variance''
			EXEC Update_Server_Log @@Step, @@Process

			UPDATE  dbo.RCardexLedgerCompare
			SET     CardexLedgerVariance = ( LedgerAmount - CardexAmount )


		--Transaction logging		
			SELECT  @err = @@error, @rowc = @@rowcount
			EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
			IF @err <> 0 BEGIN GOTO Err_Handler END


    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS




-- Assign status codes
--Manual Journal Entries
			SET @@Process = ''Identifying manual journal entries''
			EXEC Update_Server_Log @@Step, @@Process

			UPDATE  dbo.RCardexLedgerCompare
			SET     Status = ''Manual Entry''
			FROM    dbo.RCardexLedgerCompare
			WHERE   Status = ''No Cardex'' AND DocType LIKE ''J%'' AND OrderType = '' ''

		--Transaction logging		
			SELECT  @err = @@error, @rowc = @@rowcount
			EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
			IF @err <> 0 BEGIN GOTO Err_Handler END


    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS


--Unreconciled Transactions
			SET @@Process = ''Identifying unreconciled transactions''
			EXEC Update_Server_Log @@Step, @@Process

			UPDATE  RCardexLedgerCompare
			SET     Status = ''Red''
			FROM    RCardexLedgerCompare 
			INNER JOIN RConstants ON ( 1 = 1 )
			WHERE   Status = '''' AND ABS(CardexLedgerVariance) > Threshold1

		--Transaction logging		
			SELECT  @err = @@error, @rowc = @@rowcount
			EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
			IF @err <> 0 BEGIN GOTO Err_Handler END


    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS


--Success:
DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
SET		@@Process = ''Procedure completed sucessfully''
EXEC 	Update_Server_Log @@Step, @@Process 
    RETURN 0

-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 ) WITH Log
    RETURN -1
--End






' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_130_Comparison_Table] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp_131_Reconciling_Items]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_131_Reconciling_Items]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp_131_Reconciling_Items] ( @Err INT OUTPUT )
AS --******************************
-- RapidReconciler Build Reconciling Items
--******************************
    DECLARE @@Step VARCHAR(30), @@Process VARCHAR(100), @rowc INT, @Company VarChar(5)
    SET @@Step = ''131 Reconciling Table''


--Prep
    TRUNCATE TABLE	RCardexLedgerCompare2
	Update Statistics RCardexLedgerCompare2;


	Update RCardexLedgerCompare Set Status = ''Red'' Where Status = ''Mfg Accounting Required'' and InventoryAccount = ''Outside Operations''
	

If Exists (Select *
			From F4111b
			Where ILDCT = ''IW'' and ILTREX = ''Inventory Adj - Quixtar Sales '')
Begin

-- Variance Detail Table

    SET @@Process = ''Inserting NO GL into variance detail table''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RCardexLedgerCompare2
            SELECT  *
			FROM RCardexLedgerCompare A
			WHERE A.Status = ''No GL''
			AND A.DocType <> ''IW''


		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


    SET @@Process = ''Inserting No Cardex into variance detail table''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RCardexLedgerCompare2
            SELECT  *
			FROM RCardexLedgerCompare A
			WHERE A.Status = ''No Cardex''
			AND A.DocType <> ''IW''


		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


    SET @@Process = ''Inserting Red into variance detail table''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RCardexLedgerCompare2
            SELECT  *
			FROM RCardexLedgerCompare A
			WHERE A.Status = ''Red''
			AND A.DocType <> ''IW''


		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


GoTo Finished
End




-- Standard Processing

    SET @@Process = ''Inserting No GL into variance detail table''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RCardexLedgerCompare2
            SELECT  A.*
			FROM RCardexLedgerCompare A, RConstants
			WHERE A.Status = ''No GL'' And Abs(CardexLedgerVariance) > Threshold1

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


    SET @@Process = ''Inserting No Cardex into variance detail table''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RCardexLedgerCompare2
            SELECT  A.*
			FROM RCardexLedgerCompare A, RConstants
			WHERE A.Status = ''No Cardex'' And Abs(CardexLedgerVariance) > Threshold1

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


    SET @@Process = ''Inserting RED into variance detail table''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RCardexLedgerCompare2
            SELECT  A.*
			FROM RCardexLedgerCompare A, RConstants
			WHERE A.Status = ''Red'' And Abs(CardexLedgerVariance) > Threshold1

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


Finished:


    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS

Exec dbo.usp_150_Document_Mismatches @Err OUTPUT
IF @Err <> 0 
    GOTO Err_Handler



Exec dbo.usp_140_Document_Netting @Err OUTPUT
IF @Err <> 0 
    GOTO Err_Handler



Exec dbo.usp_160_Document_Analysis @Err OUTPUT
IF @Err <> 0 
    GOTO Err_Handler

-- Setting Variance on specialty accounts to zero for accurate out of balance calculations
    SET @@Process = ''Setting variance to 0 for specialty accounts''
    EXEC Update_Server_Log @@Step, @@Process

Update RCardexLedgerCompare2 Set CardexLedgerVariance = 0 Where InventoryAccount In (''Outside Operations'', ''GL Class Not In Base Table'')

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


-- Adding Flag for specialty accounts
    SET @@Process = ''Adding worked flag for specialty accounts''
    EXEC Update_Server_Log @@Step, @@Process

Insert Into RCardexLedgerCompare2WorkNote
Select	CompanyNumber, InventoryAccount, OrderType, DocType, DocNumber, PeriodEnds, MfgBatch, 1,'''',''System'',0
From	RCardexLedgerCompare2 B
Where	InventoryAccount In (''GL Class Not In Base Table'',''Outside Operations'')
		And Not Exists (Select * From RCardexLedgerCompare2WorkNote A 
						Where	A.CompanyNumber = B.CompanyNumber And
								A.InventoryAccount = B.InventoryAccount And
								A.OrderType = B.OrderType And
								A.DocType = B.DocType And
								A.DocNumber = B.DocNumber And
								A.PeriodEnds = B.PeriodEnds And
								A.MfgBatch = B.MfgBatch)

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


--Success:
DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
SET		@@Process = ''Procedure completed sucessfully''
EXEC 	Update_Server_Log @@Step, @@Process 
    RETURN 0

-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 ) WITH Log
    RETURN -1
--End' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_131_Reconciling_Items] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp_140_Document_Netting]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_140_Document_Netting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

CREATE PROCEDURE [dbo].[usp_140_Document_Netting] ( @Err INT OUTPUT )
AS --******************************
-- RapidReconciler Document Netting Module
--******************************
    DECLARE @@Step VARCHAR(30), @@Process VARCHAR (100), @rowc int
	
    SET @@Step = ''140 Document Netting''




-- Purchasing
    EXEC Net_Purchase_Receipts @Err OUTPUT
    IF @Err <> 0 
        GOTO Err_Handler




-- Manufacturing
    EXEC Net_Manufacturing_Batches @Err OUTPUT
    IF @Err <> 0 
        GOTO Err_Handler

    EXEC Net_Rate_Schedule @Err OUTPUT
    IF @Err <> 0 
        GOTO Err_Handler

    EXEC Net_WO_Cross_Reference @Err OUTPUT
    IF @Err <> 0 
        GOTO Err_Handler

    EXEC Net_Outside_Operations @Err OUTPUT
    IF @Err <> 0 
        GOTO Err_Handler

--Matched Documents
    EXEC Net_Matched_Documents @Err OUTPUT
    IF @Err <> 0 
        GOTO Err_Handler


-- Sales
    EXEC Net_Interbranch_Sales @Err OUTPUT
    IF @Err <> 0 
        GOTO Err_Handler

    EXEC Net_Intercompany_Sales @Err OUTPUT
    IF @Err <> 0 
        GOTO Err_Handler

    EXEC Net_Batch_Invoices @Err OUTPUT
    IF @Err <> 0 
        GOTO Err_Handler

    EXEC Net_Direct_Shipments @Err OUTPUT
    IF @Err <> 0 
        GOTO Err_Handler

--Miscellaneous
    EXEC Net_Misc_Transactions @Err OUTPUT
    IF @Err <> 0 
        GOTO Err_Handler

--Intercompany
    EXEC Net_Intercompany_Transactions @Err OUTPUT
    IF @Err <> 0 
        GOTO Err_Handler



-- VMI for ATS
If Exists (Select * From F4111B Where ILTREX = ''Zero Out VMI Part Transactions'')
Begin
    EXEC Net_VMI_Transactions @Err OUTPUT
    IF @Err <> 0 
        GOTO Err_Handler
End




-- Successful Completion 
DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
SET		@@Process = ''Procedure completed sucessfully''
EXEC 	Update_Server_Log @@Step, @@Process 
    RETURN 0

-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 ) WITH Log
    RETURN -1
--End












' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_140_Document_Netting] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp_150_Document_Mismatches]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_150_Document_Mismatches]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

CREATE PROCEDURE [dbo].[usp_150_Document_Mismatches] ( @Err INT OUTPUT )
AS 

--******************************
-- RapidReconciler Mismatched Transaction Procedure
--******************************

    DECLARE @@Step VARCHAR(30), @@Process VARCHAR(100), @rowc INT
    SET @@Step = ''150 Document Mismatches''

    DECLARE @Rounding DECIMAL(18, 2) SET @Rounding = .05

--Mismatched Accounts Basic Transactions in the Comparison Table
    SET @@Process = ''Mismatched accounts, simple transactions''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Mismatch: Account Number'',  Comment = ''   '' + CXGL2.InventoryAccount
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( dbo.RCardexLedgerCompare2.CompanyNumber = CXGL2.CompanyNumber AND
                 dbo.RCardexLedgerCompare2.DocType = CXGL2.DocType AND
                 dbo.RCardexLedgerCompare2.DocNumber = CXGL2.DocNumber AND
                 dbo.RCardexLedgerCompare2.OrderType = CXGL2.OrderType AND
                 dbo.RCardexLedgerCompare2.PeriodEnds = CXGL2.PeriodEnds ) 
    INNER JOIN RConstants
            ON ( 1 = 1 )
    WHERE   dbo.RCardexLedgerCompare2.Status IN ( ''No Cardex'', ''No GL'', ''Red'' ) AND
            CXGL2.Status IN ( ''No Cardex'', ''No GL'', ''Red'' ) AND
            dbo.RCardexLedgerCompare2.DocType NOT IN ( ''IC'', ''IM'', ''LM'',''LC'',''IS'' ) AND
            dbo.RCardexLedgerCompare2.InventoryAccount <> ''Outside Operations'' AND
            CXGL2.InventoryAccount <> ''Outside Operations'' AND
            dbo.RCardexLedgerCompare2.InventoryAccount <> CXGL2.InventoryAccount AND
            ABS(dbo.RCardexLedgerCompare2.CardexLedgerVariance + CXGL2.CardexLedgerVariance) <= Threshold1

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS


--Mismatched Accounts Work Order Transactions in the Comparison Table
    SET @@Process = ''Mismatched accounts, work order transactions''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Mismatch: Account Number'', Comment = ''   '' + CXGL2.InventoryAccount
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( dbo.RCardexLedgerCompare2.CompanyNumber = CXGL2.CompanyNumber AND
                 dbo.RCardexLedgerCompare2.DocType = CXGL2.DocType AND
                 dbo.RCardexLedgerCompare2.DocNumber = CXGL2.DocNumber AND
                 dbo.RCardexLedgerCompare2.PeriodEnds = CXGL2.PeriodEnds )
    WHERE   dbo.RCardexLedgerCompare2.Status IN ( ''No Cardex'', ''No GL'',''Red'' ) AND
            CXGL2.Status IN ( ''No Cardex'', ''No GL'',''Red'' ) AND
            dbo.RCardexLedgerCompare2.Status <> CXGL2.Status AND
            dbo.RCardexLedgerCompare2.DocType IN ( ''IC'', ''IM'', ''LC'',''LM'',''IS'' ) AND
            dbo.RCardexLedgerCompare2.InventoryAccount <> ''Outside Operations'' AND
            CXGL2.InventoryAccount <> ''Outside Operations'' AND
            dbo.RCardexLedgerCompare2.InventoryAccount <> CXGL2.InventoryAccount
	
		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS


--Mismatched Accounts Work Order Transactions in the Comparison Table
    SET @@Process = ''Mismatched accounts, work order reversals''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Mismatch: Account Number'', Comment = ''   '' + CXGL2.InventoryAccount
    FROM    dbo.RCardexLedgerCompare2 
	Inner Join	RConstants On (1=1)
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( dbo.RCardexLedgerCompare2.CompanyNumber = CXGL2.CompanyNumber AND
                 dbo.RCardexLedgerCompare2.DocType = CXGL2.DocType AND
                 dbo.RCardexLedgerCompare2.DocNumber = CXGL2.DocNumber AND
                 dbo.RCardexLedgerCompare2.PeriodEnds = CXGL2.PeriodEnds And
				 dbo.RCardexLedgerCompare2.Status = CXGL2.Status And
				 dbo.RCardexLedgerCompare2.MfgBatch = CXGL2.MfgBatch)
    WHERE   dbo.RCardexLedgerCompare2.Status = ''Red'' AND
            dbo.RCardexLedgerCompare2.DocType IN ( ''IC'', ''IM'', ''LC'',''LM'' ) AND
            dbo.RCardexLedgerCompare2.InventoryAccount <> ''Outside Operations'' AND CXGL2.InventoryAccount <> ''Outside Operations'' AND
            dbo.RCardexLedgerCompare2.InventoryAccount <> CXGL2.InventoryAccount And
			ABS(dbo.RCardexLedgerCompare2.CardexLedgerVariance + CXGL2.CardexLedgerVariance) < Threshold1
	
		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS





-- Interbranch

If Exists ( SELECT * FROM F0911 WHERE GLICUT = ''ST'' AND GLDCT = ''JE'' )
begin 

--Mismatched Accounts Interbranch Sales Transactions GL to GL by Order line number
    SET @@Process = ''Identifying mismatched accounts, interbranch sales''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Mismatch: Account Number'', Comment = ''   '' + CXGL2.InventoryAccount, MatchingDocument = CXGL2.DocNumber
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.F0911 GL
            ON ( dbo.RCardexLedgerCompare2.DocType = GL.GLDCT AND
                 dbo.RCardexLedgerCompare2.DocNumber = GL.GLDOC AND
                 dbo.RCardexLedgerCompare2.OrderType = GL.GLDCTO AND
                 dbo.RCardexLedgerCompare2.PeriodEnds = GL.PeriodEnds ) 
    INNER JOIN dbo.F0911 GL2
            ON ( GL.GLR1 = GL2.GLR1 AND
                 GL.GLLNID = GL2.GLLNID ) 
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( CXGL2.DocType = GL2.GLDCT AND
                 CXGL2.DocNumber = GL2.GLDOC AND
                 CXGL2.OrderType = GL2.GLDCTO AND
                 CXGL2.PeriodEnds = GL2.PeriodEnds )
    WHERE   dbo.RCardexLedgerCompare2.DocType = ''JE'' AND
            dbo.RCardexLedgerCompare2.Status IN ( ''No GL'' ) AND
            CXGL2.Status IN ( ''No Cardex'' ) AND
            dbo.RCardexLedgerCompare2.InventoryAccount <> CXGL2.InventoryAccount AND
            GL.GLICUT = ''ST'' AND
            GL2.GLICUT IN ( ''I'', ''G'' ) AND
            ABS(dbo.RCardexLedgerCompare2.CardexLedgerVariance + CXGL2.CardexLedgerVariance) <= @Rounding

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler





--Update Matching Transaction Data
    SET @@Process = ''Matching mismatched account documents, interbranch sales''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Mismatch: Account Number'', Comment = ''   '' + CXGL2.InventoryAccount, MatchingDocument = CXGL2.Docnumber
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( dbo.RCardexLedgerCompare2.PeriodEnds = CXGL2.PeriodEnds AND
                 dbo.RCardexLedgerCompare2.DocNumber = CXGL2.MatchingDocument )
    WHERE   dbo.RCardexLedgerCompare2.DocType IN ( SELECT DISTINCT DocType FROM v_RInvoiceTypes ) AND
            CXGL2.DocType = ''JE'' AND
            dbo.RCardexLedgerCompare2.InventoryAccount <> CXGL2.InventoryAccount AND
            CXGL2.Status = ''Mismatch: Account Number'' AND
            ABS(dbo.RCardexLedgerCompare2.CardexLedgerVariance + CXGL2.CardexLedgerVariance) <= @Rounding

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler





--Mismatched Accounts Interbranch Sales GL to Cardex by order line number JE to RI
    SET @@Process = ''Identifying mismatched accounts, JE to RI''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Mismatch: Account Number'',
            Comment = ''   '' + CXGL2.InventoryAccount, MatchingDocument = CXGL2.Docnumber
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN F0911 GL
            ON ( dbo.RCardexLedgerCompare2.CompanyNumber = GL.GLCO AND
                 dbo.RCardexLedgerCompare2.InventoryAccount = GL.GLANI AND
                 dbo.RCardexLedgerCompare2.PeriodEnds = GL.PeriodEnds AND
                 dbo.RCardexLedgerCompare2.DocType = GL.GLDCT AND
                 dbo.RCardexLedgerCompare2.DocNumber = GL.GLDOC ) 
    INNER JOIN F4111B CX
            ON ( GL.GLR1 = CX.ILDOCO AND
                 GL.GLDCTO = CX.ILDCTO AND
                 GL.GLDGJ = CX.ILDGL ) 
    INNER JOIN RCardexLedgerCompare2 CXGL2
            ON ( CXGL2.CompanyNumber = CX.ILKCO AND
                 CXGL2.InventoryAccount = CX.InventoryAccount AND
                 CXGL2.PeriodEnds = CX.PeriodEnds AND
                 CXGL2.DocType = CX.ILDCT AND
                 CXGL2.DocNumber = CX.ILDOC AND
                 CXGL2.OrderType = CX.ILDCTO ) 
    INNER JOIN v_RInvoiceTypes IT
            ON ( dbo.RCardexLedgerCompare2.DocType = IT.DocType )
    WHERE   dbo.RCardexLedgerCompare2.Status IN ( ''No Cardex'' ) AND
            GL.GLICUT = ''I'' AND
            dbo.RCardexLedgerCompare2.InventoryAccount <> CXGL2.InventoryAccount AND
            ABS(dbo.RCardexLedgerCompare2.CardexLedgerVariance + CXGL2.CardexLedgerVariance) <= @Rounding

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler






--Mismatched Accounts Interbranch Sales GL to Cardex by order line number JE to JE
    SET @@Process = ''Identifying mismatched accounts, JE to JE''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Mismatch: Account Number'', Comment = ''   '' + CXGL2.InventoryAccount,  MatchingDocument = CXGL2.Docnumber
	From RCardexLedgerCompare2
    INNER JOIN F0911 GL
            ON ( dbo.RCardexLedgerCompare2.CompanyNumber = GL.GLCO AND
                 dbo.RCardexLedgerCompare2.InventoryAccount = GL.GLANI AND
                 dbo.RCardexLedgerCompare2.PeriodEnds = GL.PeriodEnds AND
                 dbo.RCardexLedgerCompare2.DocType = GL.GLDCT AND
                 dbo.RCardexLedgerCompare2.DocNumber = GL.GLDOC ) 
    INNER JOIN F4111B CX
            ON ( GL.GLR1 = CX.ILDOCO AND
                 GL.GLDCTO = CX.ILDCTO AND
                 GL.GLDGJ = CX.ILDGL ) 
    INNER JOIN RCardexLedgerCompare2 CXGL2
            ON ( CXGL2.CompanyNumber = CX.ILKCO AND
                 CXGL2.InventoryAccount = CX.InventoryAccount AND
                 CXGL2.PeriodEnds = CX.PeriodEnds AND
                 CXGL2.DocType = CX.ILDCT AND
                 CXGL2.DocNumber = CX.ILDOC AND
                 CXGL2.OrderType = CX.ILDCTO )
    WHERE   dbo.RCardexLedgerCompare2.Status IN ( ''No Cardex'' ) AND
            GL.GLICUT = ''ST'' AND
            dbo.RCardexLedgerCompare2.InventoryAccount <> CXGL2.InventoryAccount AND
            ABS(dbo.RCardexLedgerCompare2.CardexLedgerVariance + CXGL2.CardexLedgerVariance) <= @Rounding

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler



--Update Matching Transaction Data
    SET @@Process = ''Matching mismatched accounts, JE to JE 2''
    EXEC Update_Server_Log @@Step, @@Process	

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Mismatch: Account Number'', Comment = ''   '' + CXGL2.InventoryAccount, MatchingDocument = CXGL2.Docnumber
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN RCardexLedgerCompare2 CXGL2
            ON ( dbo.RCardexLedgerCompare2.DocNumber = CXGL2.MatchingDocument AND
                 dbo.RCardexLedgerCompare2.PeriodEnds = CXGL2.PeriodEnds )
    WHERE   dbo.RCardexLedgerCompare2.Status IN ( ''No GL'' ) AND
            dbo.RCardexLedgerCompare2.DocType = ''JE'' AND
            dbo.RCardexLedgerCompare2.InventoryAccount <> CXGL2.InventoryAccount AND
            CXGL2.Status = ''Mismatch: Account Number'' AND
            ABS(dbo.RCardexLedgerCompare2.CardexLedgerVariance + CXGL2.CardexLedgerVariance) <= @Rounding

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler


--Interbranch Variance
    SET @@Process = ''Identifying interbranch variance''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Interbranch Variance'',
            Comment = ''   '' + CXGL2.DocType + '' '' + CONVERT(CHAR, CXGL2.DocNumber), MatchingDocument = CXGL2.DocNumber
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.F0911 GL
            ON ( dbo.RCardexLedgerCompare2.CompanyNumber = GL.GLCO AND
                 dbo.RCardexLedgerCompare2.InventoryAccount = GL.GLANI AND
                 dbo.RCardexLedgerCompare2.PeriodEnds = GL.PeriodEnds AND
                 dbo.RCardexLedgerCompare2.DocType = GL.GLDCT AND
                 dbo.RCardexLedgerCompare2.DocNumber = GL.GLDOC ) 
    INNER JOIN dbo.F0911 GL2
            ON ( GL.GLCO = GL2.GLCO AND
                 GL.GLANI = GL2.GLANI AND
                 GL.GLR1 = GL2.GLR1 AND
                 GL.GLLNID = GL2.GLLNID ) 
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( CXGL2.CompanyNumber = GL2.GLCO AND
                 CXGL2.InventoryAccount = GL2.GLANI AND
                 CXGL2.PeriodEnds = GL2.PeriodEnds AND
                 CXGL2.DocTYpe = GL2.GLDCT AND
                 CXGL2.DocNumber = GL2.GLDOC ) 
    INNER JOIN dbo.RConstants Const
            ON ( 1 = 1 )
    WHERE   dbo.RCardexLedgerCompare2.Status IN ( ''No Cardex'' ) AND
            dbo.RCardexLedgerCompare2.DocType = ''JE'' AND
            GL.GLICUT = ''ST'' AND
            GL2.GLICUT IN ( ''I'', ''G'' ) 

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler




--Matching
    SET @@Process = ''Matching interbranch variance''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Interbranch Variance '', Comment = ''   JE '' + CONVERT(CHAR, CXGL2.DocNumber), MatchingDocument = CXGL2.Docnumber
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( dbo.RCardexLedgerCompare2.CompanyNumber = CXGL2.CompanyNumber AND
                 dbo.RCardexLedgerCompare2.InventoryAccount = CXGL2.InventoryAccount AND
                 dbo.RCardexLedgerCompare2.PeriodEnds = CXGL2.PeriodEnds AND
                 dbo.RCardexLedgerCompare2.DocNumber = CXGL2.MatchingDocument ) 
    INNER JOIN v_RInvoiceTypes T
            ON ( dbo.RCardexLedgerCompare2.DocType = T.DocType )
    WHERE   dbo.RCardexLedgerCompare2.Status IN ( ''No Cardex'' ) AND
            CXGL2.Status LIKE ''Interbranch Variance%'' AND
            CXGL2.DocType = ''JE''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler



    SET @@Process = ''Identifying interbranch variance 2''
    EXEC Update_Server_Log @@Step, @@Process
    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Interbranch Variance''
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.F4111B CX
            ON ( CX.PeriodEnds = dbo.RCardexLedgerCompare2.PeriodEnds AND
                 CX.ILDCT = dbo.RCardexLedgerCompare2.DocType AND
                 CX.ILDOC = dbo.RCardexLedgerCompare2.DocNumber )
    WHERE   dbo.RCardexLedgerCompare2.Status = ''No Cardex'' AND
            dbo.RCardexLedgerCompare2.Doctype = ''JE'' AND
            dbo.RCardexLedgerCompare2.CompanyNumber <> CX.ILKCO

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler




-- Update Matching document numbers for mismatched accounts for interbranch variance
    SET @@Process = ''Updating matching document numbers for I/B variance''
    EXEC Update_Server_Log @@Step, @@Process
    UPDATE  dbo.RCardexLedgerCompare2
    SET     MatchingDocument = CXGL2.MatchingDocument, Comment = CXGL2.Comment
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( dbo.RCardexLedgerCompare2.PeriodEnds = CXGL2.PeriodEnds AND
                 dbo.RCardexLedgerCompare2.DocType = CXGL2.DocType AND
                 dbo.RCardexLedgerCompare2.DocNumber = CXGL2.DocNumber )
    WHERE   dbo.RCardexLedgerCompare2.Status = ''Interbranch Variance'' AND
            dbo.RCardexLedgerCompare2.MatchingDocument = 0 AND
            dbo.RCardexLedgerCompare2.CompanyNumber <> CXGL2.CompanyNumber

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler


--Re Class Interbranch Variance
    SET @@Process = ''Reclassifying variance''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RCardexLedgerCompare2
    SET     Status = ''Mismatch: Account Number'', Comment = ''   '' + InventoryAccount
    FROM    dbo.RCardexLedgerCompare2,
            ( SELECT    PeriodEnds,
                        MatchingDocument,
                        SUM(CardexLedgerVariance) AS Variance
              FROM      dbo.RCardexLedgerCompare2 CXGL2
              WHERE     CXGL2.Status = ''Interbranch Variance'' AND
                        CXGL2.DocType = ''JE''
              GROUP BY  PeriodEnds,
                        MatchingDocument ) AS T
    WHERE   dbo.RCardexLedgerCompare2.Status = ''Interbranch Variance'' AND
            dbo.RCardexLedgerCompare2.PeriodEnds = T.PeriodEnds AND
            dbo.RCardexLedgerCompare2.DocNumber = T.MatchingDocument AND
            ABS(dbo.RCardexLedgerCompare2.CardexLedgerVariance + T.Variance) < @Rounding

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler


    SET @@Process = ''Matching reclassified variance''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RCardexLedgerCompare2
    SET     Status = ''Mismatch: Account Number'', Comment = ''   '' + CXGL2.InventoryAccount
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( dbo.RCardexLedgerCompare2.DocNumber = CXGL2.MatchingDocument AND
                 dbo.RCardexLedgerCompare2.PeriodEnds = CXGL2.PeriodEnds )
    WHERE   dbo.RCardexLedgerCompare2.Status = ''Interbranch Variance'' AND
            CXGL2.Status = ''Mismatch: Account Number''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler



-- Reclass to Red or Green
    SET @@Process = ''Updating red/green status''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = CASE WHEN ABS(dbo.RCardexLedgerCompare2.CardexLedgerVariance - CXGL2.CardexLedgerVariance) <= CONST.Threshold1 THEN ''Green''
                          WHEN ABS(dbo.RCardexLedgerCompare2.CardexLedgerVariance - CXGL2.CardexLedgerVariance) > CONST.Threshold1 THEN ''Red''
                     END
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.RConstants CONST
            ON ( 1 = 1 ) 
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( dbo.RCardexLedgerCompare2.DocNumber = CXGL2.MatchingDocument AND
                 dbo.RCardexLedgerCompare2.PeriodEnds = CXGL2.PeriodEnds )
    WHERE   dbo.RCardexLedgerCompare2.Status = ''Interbranch Variance''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS

end


-- Mismatched Periods


-- Cardex to GL
    SET @@Process = ''Identifying mismatched periods, CX to GL''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Mismatch: Period'', Comment = ''   Offset Period: '' + CONVERT(VARCHAR, CXGL2.PeriodEnds, 101)
	FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( dbo.RCardexLedgerCompare2.CompanyNumber = CXGL2.CompanyNumber AND
                 dbo.RCardexLedgerCompare2.InventoryAccount = CXGL2.InventoryAccount AND
                 dbo.RCardexLedgerCompare2.DocType = CXGL2.DocType AND
                 dbo.RCardexLedgerCompare2.DocNumber = CXGL2.DocNumber )
    WHERE   dbo.RCardexLedgerCompare2.Status in (''Red'', ''No GL'', ''No Cardex'') AND CXGL2.Status in (''Red'', ''No GL'', ''No Cardex'') AND
            dbo.RCardexLedgerCompare2.PeriodEnds <> CXGL2.PeriodEnds AND
            ABS(dbo.RCardexLedgerCompare2.CardexLedgerVariance + CXGL2.CardexLedgerVariance) <= .05

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler


    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS



-- GL Reversals
    SET @@Process = ''Identifying mismatched periods GL reversals''
    EXEC Update_Server_Log @@Step, @@Process


    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Mismatch: Period'', Comment = ''   Offset Period: '' + CONVERT(VARCHAR, CXGL2.PeriodEnds, 101)
	FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( dbo.RCardexLedgerCompare2.CompanyNumber = CXGL2.CompanyNumber AND
                 dbo.RCardexLedgerCompare2.InventoryAccount = CXGL2.InventoryAccount AND
                 dbo.RCardexLedgerCompare2.DocType = CXGL2.DocType AND
                 dbo.RCardexLedgerCompare2.DocNumber = CXGL2.DocNumber)
    WHERE   dbo.RCardexLedgerCompare2.Status = ''No Cardex'' AND CXGL2.Status = ''No Cardex'' AND
            dbo.RCardexLedgerCompare2.PeriodEnds <> CXGL2.PeriodEnds AND
            dbo.RCardexLedgerCompare2.CardexLedgerVariance + CXGL2.CardexLedgerVariance <= .05

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS



--Mismatch Periods Future  - GL Side
    SET @@Process = ''Identifying mismatched periods future GL''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Mismatch: Period'', Comment = ''Offset Period: '' + CONVERT(VARCHAR, CXGL2.PeriodEnds, 101)
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( dbo.RCardexLedgerCompare2.CompanyNumber = CXGL2.CompanyNumber AND
                 dbo.RCardexLedgerCompare2.DocType = CXGL2.DocType AND
                 dbo.RCardexLedgerCompare2.DocNumber = CXGL2.DocNumber AND
                 dbo.RCardexLedgerCompare2.OrderType = CXGL2.OrderType )
    WHERE   dbo.RCardexLedgerCompare2.Status IN ( ''Mismatch: Account Number'',
                                                 ''No GL'', ''No Cardex'' ) AND
            dbo.RCardexLedgerCompare2.InventoryAccount = ''Future GL'' AND
            ABS(dbo.RCardexLedgerCompare2.CardexLedgerVariance + CXGL2.CardexLedgerVariance) <= .05

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS



--Mismatch Periods Future CX Side
    SET @@Process = ''Identifying mismatched periods future CX''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RCardexLedgerCompare2
    SET     Status = ''Mismatch: Period'', Comment = ''Offset Period: '' + CONVERT(VARCHAR, CXGL2.PeriodEnds, 101)
    FROM    dbo.RCardexLedgerCompare2 
    INNER JOIN dbo.RCardexLedgerCompare2 CXGL2
            ON ( dbo.RCardexLedgerCompare2.CompanyNumber = CXGL2.CompanyNumber AND
                 dbo.RCardexLedgerCompare2.DocType = CXGL2.DocType AND
                 dbo.RCardexLedgerCompare2.DocNumber = CXGL2.DocNumber AND
                 dbo.RCardexLedgerCompare2.OrderType = CXGL2.OrderType )
    WHERE   dbo.RCardexLedgerCompare2.Status IN ( ''Mismatch: Account Number'',
                                                 ''No GL'', ''No Cardex'' ) AND
            CXGL2.InventoryAccount = ''Future GL'' AND
            ABS(dbo.RCardexLedgerCompare2.CardexLedgerVariance + CXGL2.CardexLedgerVariance) <= .05

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler





-- Successful Completion
DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
SET		@@Process = ''Procedure completed sucessfully''
EXEC 	Update_Server_Log @@Step, @@Process 
    RETURN 0


    err_handler:
    RETURN 1



' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_150_Document_Mismatches] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp_160_Document_Analysis]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_160_Document_Analysis]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE     PROCEDURE [dbo].[usp_160_Document_Analysis] ( @Err INT OUTPUT )
AS

 
DECLARE @@Step VARCHAR(30), @@Process VARCHAR(100), @rowc INT, @DocType Varchar(2)
SET @@Step = ''160 Document Analysis''


-- Sales Transactions
-- Prep Sales Tables
SET @@Process = ''Preparing Sales Data ... ''
EXEC Update_Server_Log @@Step, @@Process

-- Invoice Types
SET @@Process = ''Build Invoice Types Table ... ''
EXEC Update_Server_Log @@Step, @@Process

Declare		@SalesTypes Table (DocType Varchar(2))

Insert Into @SalesTypes
Select Distinct GLDCT From F0911 Where GLICUT In (''I'',''IB'',''ST'') And Exists (Select * From RCardexLedgerCompare2 Where GLDCT = DocType)

	--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler



-- Kits Table
--SET @@Process = ''Build Kit Table ... ''
--EXEC Update_Server_Log @@Step, @@Process
--
--
--Declare @Kit_Ship Table(CompanyNumber Varchar(5), DocType Varchar(2), DocNumber Decimal(8,0), OrderType Varchar(2), Cost Decimal(18,2))
--
--Insert Into		@Kit_Ship
--	SELECT		SDCO, SDDCT, SDDOC, SDDCT, SUM(SDECST) AS SDECST
--	FROM		F42119 
--	INNER JOIN	vcr_F4101 ON ( SDLITM = IMLITM )
--	WHERE		IMSTKT = ''K''
--	GROUP BY	SDCO, SDDCTO, SDDOC, SDDCT 
--
--	--Transaction logging		
--SELECT  @err = @@error, @rowc = @@rowcount
--EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
--IF @err <> 0 GOTO Err_Handler



--Multiple Shipments
SET @@Process = ''Build Multiship Table ... ''
EXEC Update_Server_Log @@Step, @@Process

Declare @Mult_Ship Table(CompanyNumber Varchar(5), DocType Varchar(2), DocNumber Decimal(8,0), OrderType Varchar(2))

Insert Into	@Mult_Ship
			Select ILKCO, ILDCT, ILDOC, ILDCTO
			From F4111B
			Where ILDCT In (Select * From v_RInvoiceTypes) And ILTREX <> ''Standard Cost Change''
			Group By ILKCO, ILDCT, ILDOC, ILDCTO, ILDOCO, ILLNID
			Having Count(*) > 1

	--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler


-- Missing Cardex Table
SET @@Process = ''Build Missing Cardex Table ... ''
EXEC Update_Server_Log @@Step, @@Process

Declare @Missing_Cardex Table(CompanyNumber Varchar(5),  DocType Varchar(2),  DocNumber Decimal(8,0), OrderType Varchar(2))

Insert Into	@Missing_Cardex
		Select  Distinct SDCO, SDDCT, SDDOC, SDDCTO
		From	F42119
	    Inner Join	RCompanies On (SDCO = CompanyNumber)
		Where	SDSO02 = 1 And SDDCTO <> ''SQ'' And SDDOC > 0 
				And Not Exists 
				(Select * 
				 From F4111B
				 Where ILKCO = SDCO And	SDDCTO = ILDCTO And SDDOCO = ILDOCO And SDLNID = ILLNID)

	--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler



-- Line Types Table
SET @@Process = ''Build Line Type Table ... ''
EXEC Update_Server_Log @@Step, @@Process

Declare @Line_Types Table(CompanyNumber Varchar(5),  DocType Varchar(2),  DocNumber Decimal(8,0), OrderType Varchar(2), LineType Varchar(2), GLClass Varchar(4), Cost Decimal(18,2))

Insert Into @Line_Types
Select Distinct		SDCO, SDDCT, SDDOC, SDDCTO, SDLNTY, SDGLC, Sum(SDECST)
From				F4211
Inner Join			RCardexLedgerCompare2 On (SDCO = CompanyNumber And SDDCT = DocType And SDDOC = DocNumber And SDDCTO = OrderType)
Where				Status = ''No Cardex''
Group By			SDCO, SDDCT, SDDOC, SDDCTO, SDLNTY, SDGLC, CardexLedgerVariance
Having				Sum(SDECST) + CardexLedgerVariance = 0

Insert Into @Line_Types
Select Distinct		SDCO, SDDCT, SDDOC, SDDCTO, SDLNTY, SDGLC, Sum(SDECST)
From				F42119
Inner Join			RCardexLedgerCompare2 On (SDCO = CompanyNumber And SDDCT = DocType And SDDOC = DocNumber And SDDCTO = OrderType)
Where				Status = ''No Cardex''
Group By			SDCO, SDDCT, SDDOC, SDDCTO, SDLNTY, SDGLC, CardexLedgerVariance
Having				Sum(SDECST) + CardexLedgerVariance = 0

	--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler


-- Cardex_Sales_Variance Table
SET @@Process = ''Build Cardex Sales Table ... ''
EXEC Update_Server_Log @@Step, @@Process


Declare @Cardex_Sales Table(CompanyNumber Varchar(5), Account Varchar(29), PeriodEnds SmallDateTime, DocType Varchar(2), DocNumber Decimal(8,0), OrderType Varchar(2), Comment Varchar(50))

Insert Into @Cardex_Sales
		Select	  ILKCO, InventoryAccount, A.PeriodEnds, ILDCT, ILDOC, ILDCTO,
        CASE WHEN ILUNCS <> SDUNCS And SDKCOO = SDCO THEN ''Cardex/Sales cost variance '' + CAST(ILDOCO AS VARCHAR) + '' '' + ILDCTO + '' '' + CAST(ILLNID AS VARCHAR)
             WHEN ILUNCS <> SDTCST And SDKCOO <> SDCO THEN ''Interco Cardex/Sales variance '' + CAST(ILDOCO AS VARCHAR) + '' '' + ILDCTO + '' '' + CAST(ILLNID AS VARCHAR)
  			 WHEN ILTRQT +  SDPQOR <> 0 THEN ''Qty changed after ship confirm '' + CAST(ILDOCO AS VARCHAR) + '' '' + ILDCTO + '' '' + CAST(ILLNID AS VARCHAR)
			 WHEN SDTCST = 0 AND SDSO01 = ''1'' THEN ''Transfer Cost $0 - I/B Doc JE '' + RTRIM(CONVERT(CHAR, ILDOC)) + '' '' + SDDCTO + '' '' + RTRIM(CONVERT(CHAR, SDDOCO))
			 WHEN SDCSTO = ''1'' THEN ''Cost Override Flag Set''
             ELSE '''' END As Comment
        FROM    F4111B A
		--Inner Join RCompanies On ILKCO = CompanyNumber
        INNER JOIN F42119 B ON (SDKCOO = ILKCOO AND SDCO = ILKCO AND SDDOCO = ILDOCO AND SDDCTO = ILDCTO AND SDLNID = ILLNID and A.PeriodEnds = B.PeriodEnds And ILLITM = SDLITM)

	--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler


-- Transaction explanations Table Sales
SET @@Process = ''Build Trex Table Sales... ''
EXEC Update_Server_Log @@Step, @@Process


Declare @Trex_Sales Table(CompanyNumber Varchar(5), Account Varchar(29), PeriodEnds SmallDateTime, DocType Varchar(2), DocNumber Decimal(8,0), TRex Varchar(50))

Insert Into		@Trex_Sales
Select Distinct ILKCO, InventoryAccount, PeriodEnds, ILDCT, ILDOC, RTrim(ILTREX)
From			F4111B
Where			ILDCT In (Select * From @SalesTypes) And ILTREX <> ''''

	--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler




-- Perform Sales Analysis
    DECLARE C1 CURSOR FOR 
	Select DocType From @SalesTypes

    OPEN C1
    FETCH NEXT FROM C1 INTO @DocType
    WHILE 		@@FETCH_STATUS = 0
    BEGIN

    SET @@Process = ''Analyzing Sales Variance; '' + @DocType
    EXEC Update_Server_Log @@Step, @@Process


--	Update	RCardexLedgerCompare2
--	Set		Comment = (Select dbo.ufn_Sales_Analysis (CompanyNumber, InventoryAccount, PeriodEnds, DocType, DocNumber, OrderType, CardexAmount))
--	From	RCardexLedgerCompare2
--	Where	Comment = '''' And DocType = @DocType

	-- Kit doubling cost Issue
--				Update	RCardexLedgerCompare2
--				Set		Comment = ''Kit Item doubled the cost''
--				FROM    RCardexLedgerCompare2 A
--				Inner Join Kit_Ship B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber And A.OrderType = B.OrderType)
--				WHERE   A.CardexLedgerVariance + B.Cost = 0 And A.DocType = @DocType

	-- Multiple shipments
				Update	RCardexLedgerCompare2
				Set		Comment = ''Multiple shipments in cardex''
				FROM    RCardexLedgerCompare2 A
				Inner Join @Mult_Ship B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber And A.OrderType = B.OrderType)
				WHERE   A.DocType = @DocType And Comment = ''''

	-- Missing cardex
				Update	RCardexLedgerCompare2
				Set		Comment = ''Cardex missing sales line''
				FROM    RCardexLedgerCompare2 A
				Inner Join @Missing_Cardex B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber And A.OrderType = B.OrderType)
				WHERE   A.DocType = @DocType  And Comment = ''''

	-- Direct Ship Mismatch
				Update	RCardexLedgerCompare2
				Set		Comment = ''Direct Ship Mismatch''
				From	RCardexLedgerCompare2 A
				Where	OrderType In (Select Distinct SDDCTO From F42119 Where SDLNTY = ''D'') And A.DocType = @DocType

	-- Non Stock Lines
				Update	RCardexLedgerCompare2
				Set		Comment = ''Non Stock Line Type '' + LineType + '' GL Class '' + GLClass
				From	RCardexLedgerCompare2 A
				Inner Join	@Line_Types B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber And A.OrderType = B.OrderType)
				Where	Status = ''No Cardex'' And A.DocType = @DocType And Comment = ''''

	-- Cost/Quantity Changes
 				Update	RCardexLedgerCompare2
				Set		Comment = B.Comment
				From	RCardexLedgerCompare2 A
				Inner Join	@Cardex_Sales B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber And A.OrderType = B.OrderType)
				Where	A.DocType = @DocType And A.Comment = ''''

	-- JDE Comments
				Update	RCardexLedgerCompare2
				Set		Comment = Trex
				FROM    RCardexLedgerCompare2 A
				Inner Join @Trex_Sales B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber)
				WHERE   A.DocType = @DocType  And Comment = ''''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = (Select Count(*) From RCardexLedgerCompare2 Where DocType = @DocType and Comment <> '''')
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler


            FETCH NEXT FROM C1 INTO @DocType 
    END

    CLOSE C1
    DEALLOCATE C1

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS









--Manufacturing **********************************************************************
--Prep Manufacturing tables
SET @@Process = ''Preparing Mfg Data ... ''
EXEC Update_Server_Log @@Step, @@Process

-- Determine manufacturing document types
SET @@Process = ''Bulid Mfg Type Table ... ''
EXEC Update_Server_Log @@Step, @@Process

Declare @MfgTypes Table (DocType Varchar(2))
Insert Into @MfgTypes
Select Distinct GLDCT From F0911 Where GLICUT In (''0'',''NC'')  And Exists (Select * From RCardexLedgerCompare2 Where GLDCT = DocType)

		--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler




-- Outside operations table
SET @@Process = ''Build Outside Ops Table ... ''
EXEC Update_Server_Log @@Step, @@Process


Declare @Outside_Ops Table (CompanyNumber Varchar(5), DocType Varchar(2), DocNumber Decimal(8,0), MfgBatch Decimal(8,0))

Insert Into	@Outside_Ops
Select Distinct		CompanyNumber, Doctype, DocNumber, MfgBatch
From				RCardexLedgerCompare2
Where				InventoryAccount = ''Outside Operations'' And DocType Not In (''OV'',''IM'', ''LM'')

		--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler


-- Frozen Cost Variance Table
SET @@Process = ''Build Frozen Cost Variance Table ... ''
EXEC Update_Server_Log @@Step, @@Process


Declare @Frozen_Cost_Var Table (CompanyNumber Varchar(5), DocType Varchar(2), DocNumber Decimal(8,0), ItemNumber VarChar(25), MfgBatch Decimal(8,0))

Insert Into	@Frozen_Cost_Var
			SELECT		ILKCO, ILDCT, ILDOC, ILITM, ILICU
            FROM		F4111B
            INNER JOIN	RInvCosts A ON ( ILITM = A.ShortItem )
			INNER JOIN	RPerpetualInv B On (ILMCU = B.BranchPlant And ILITM = B.ShortItem And ILLOCN = B.Location And ILLOTN = B.Lot)
            WHERE  		ILDCT In (Select * From @MfgTypes) And A.CostLevel = 1 And ILLITM NOT LIKE ''%*OP%'' AND StockingType NOT IN ( ''C'', ''K'' ) And A.CostMethod = ''07''
			GROUP BY	ILKCO, ILDCT, ILDOC, ILITM, ILICU
			Having		Sum(ILPAID) <> Sum(Cast(FrozenCost * ILTRQT AS DECIMAL(18, 2)))
Insert Into	@Frozen_Cost_Var
			SELECT		ILKCO, ILDCT, ILDOC, ILITM, ILICU
            FROM		F4111B
            INNER JOIN	RInvCosts A ON ( ILITM = A.ShortItem And ILMCU = A.BranchPlant )
			INNER JOIN	RPerpetualInv B On (ILMCU = B.BranchPlant And ILITM = B.ShortItem And ILLOCN = B.Location And ILLOTN = B.Lot)
            WHERE  		ILDCT In (Select * From @MfgTypes) And A.CostLevel = 2 And ILLITM NOT LIKE ''%*OP%'' AND StockingType NOT IN ( ''C'', ''K'' ) And A.CostMethod = ''07''
			GROUP BY	ILKCO, ILDCT, ILDOC, ILITM, ILICU
			Having		Sum(ILPAID) <> Sum(Cast(FrozenCost * ILTRQT AS DECIMAL(18, 2)))
Insert Into	@Frozen_Cost_Var
			SELECT		ILKCO, ILDCT, ILDOC, ILITM, ILICU
            FROM		F4111B
            INNER JOIN	RInvCosts A ON ( ILITM = A.ShortItem And ILMCU = A.BranchPlant And ILLOCN = A.Location And ILLOTN = A.Lot )
			INNER JOIN	RPerpetualInv B On (ILMCU = B.BranchPlant And ILITM = B.ShortItem And ILLOCN = B.Location And ILLOTN = B.Lot)
            WHERE  		ILDCT In (Select * From @MfgTypes) And A.CostLevel = 3 And ILLITM NOT LIKE ''%*OP%'' AND StockingType NOT IN ( ''C'', ''K'' ) And A.CostMethod = ''07''
			GROUP BY	ILKCO, ILDCT, ILDOC, ILITM, ILICU
			Having		Sum(ILPAID) <> Sum(Cast(FrozenCost * ILTRQT AS DECIMAL(18, 2)))

		--Transaction logging		
SELECT  @err = @@error, @rowc = (Select Count(*) From @Frozen_Cost_Var)
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler




-- Transaction explanations Table Mfg
SET @@Process = ''Build Trex Table Mfg... ''
EXEC Update_Server_Log @@Step, @@Process

Declare @Trex_Mfg Table(CompanyNumber Varchar(5), Account Varchar(29), PeriodEnds SmallDateTime, DocType Varchar(2), DocNumber Decimal(8,0), TRex Varchar(50))

Insert Into	@Trex_Mfg
Select	Distinct ILKCO, InventoryAccount, PeriodEnds, ILDCT, ILDOC, RTrim(ILTREX)
From	F4111B
Where	ILDCT In (Select * From @MfgTypes) And ILTREX <> ''''

		--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler





-- Perform Manufacturing Analysis
    DECLARE C1 CURSOR FOR 
	Select * From @MfgTypes

    OPEN C1
    FETCH NEXT FROM C1 INTO @DocType
    WHILE 		@@FETCH_STATUS = 0
    BEGIN

    SET @@Process = ''Analyzing Mfg Variance; '' + @DocType
    EXEC Update_Server_Log @@Step, @@Process

--	Update	RCardexLedgerCompare2
--	Set		Comment = (Select dbo.ufn_Mfg_Analysis (CompanyNumber, InventoryAccount, PeriodEnds, DocType, DocNumber, OrderType, MfgBatch, Status))
--	From	RCardexLedgerCompare2
--	Where	Comment = '''' And DocType = @DocType And InventoryAccount <> ''Outside Operations''


	-- Labor or Variance in inventory
				Update	RCardexLedgerCompare2
				Set		Comment = ''Mfg expenses in inventory account''
				FROM    RCardexLedgerCompare2 A
				WHERE   A.DocType = @DocType And Comment = '''' And @DocType In (''IH'',''IV'') And Status = ''No Cardex''


	-- Manufacturing Scrap
				Update	RCardexLedgerCompare2
				Set		Comment = ''Mfg scrap in inventory account''
				FROM    RCardexLedgerCompare2 A
				WHERE   A.DocType = @DocType And Comment = '''' And @DocType = ''IS'' And Status = ''No GL''


	-- Outside Operations
				Update	RCardexLedgerCompare2
				Set		Comment = ''Outside operations in inventory account''
				From	RCardexLedgerCompare2 A
				Inner Join @Outside_Ops B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber And A.MfgBatch = B.MfgBatch)
				Where	A.DocType = @DocType And A.DocType = ''IM'' And A.InventoryAccount <> ''Outside Operations''


	-- Frozen Cost Variance
				Update	RCardexLedgerCompare2
				Set		Comment = ''Frozen Cost Variance''
				From	RCardexLedgerCompare2 A
				Inner Join @Frozen_Cost_Var B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber And A.MfgBatch = B.MfgBatch)
				Where	A.DocType = @DocType And Status = ''Red''

	-- JDE Comments
				Update	RCardexLedgerCompare2
				Set		Comment = Trex
				FROM    RCardexLedgerCompare2 A
				Inner Join @Trex_Mfg B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber)
				WHERE   A.DocType = @DocType  And Comment = ''''


		--Transaction logging		
    SELECT  @err = @@error, @rowc = (Select Count(*) From RCardexLedgerCompare2 Where DocType = @DocType and Comment <> '''')
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler

            FETCH NEXT FROM C1 INTO @DocType 
    END

    CLOSE C1
    DEALLOCATE C1



--Net work orders by document number
SET @@Process = ''Netting work orders by document''
EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RCardexLedgerCompare2
    SET     Status = ''Document Match'',
            Comment = ''Work Orders by Document''
    FROM    RCardexLedgerCompare2,
            ( SELECT    CompanyNumber,InventoryAccount, PeriodEnds, DocType, DocNumber, Mfgbatch
              FROM      RCardexLedgerCompare2 
              INNER JOIN RConstants ON ( 1 = 1 )
              WHERE     Status IN ( ''Red'', ''No Cardex'', ''No GL'' ) AND DocType IN ( ''IC'', ''IM'', ''LC'',''LM'' ) AND MfgBatch > 0
              GROUP BY  CompanyNumber, InventoryAccount, PeriodEnds, DocType, DocNumber, MfgBatch, Threshold1
              HAVING    ABS(SUM(CardexLedgerVariance)) < Threshold1 ) AS T
    WHERE   RCardexLedgerCompare2.CompanyNumber = T.CompanyNumber AND
            RCardexLedgerCompare2.InventoryAccount = T.InventoryAccount AND
            RCardexLedgerCompare2.PeriodEnds = T.PeriodEnds AND
            RCardexLedgerCompare2.DocType = T.DocType AND
            RCardexLedgerCompare2.DocNumber = T.DocNumber And
			RCardexLedgerCompare2.MfgBatch = T.MfgBatch

	--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler


If Exists	(Select * From RCardexLedgerCompare2 Where Status = ''Document Match'')
			Begin Exec usp_Remove_Netted_Transactions ''Mfg Batches''	End

DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS













-- Purchasing **********************************************************************
--Prep Purchasing tables
SET @@Process = ''Preparing Purch Data ... ''
EXEC Update_Server_Log @@Step, @@Process


-- Build Purchasing Type Table
SET @@Process = ''Build Purchasing Type Table ... ''
EXEC Update_Server_Log @@Step, @@Process

Declare @PurchTypes Table (DocType Varchar(2))
Insert Into @PurchTypes
Select Distinct GLDCT From F0911 Where GLICUT In (''O'',''V'') And Exists (Select * From RCardexLedgerCompare2 Where GLDCT = DocType)


If Not Exists (Select * From @PurchTypes Where DocType = ''PV'')
Begin
Insert Into @PurchTypes Values (''PV'')
End

	--Transaction logging		
SELECT  @err = @@error, @rowc = (Select Count(*) From @PurchTypes)
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler



-- Build Out_Ops Tables
If Exists (Select * From RCardexLedgerCompare2 Where InventoryAccount = ''Outside Operations'')
Begin

	SET @@Process = ''Build Out_Ops_Rec Table ... ''
	EXEC Update_Server_Log @@Step, @@Process

	Declare @Out_Ops_Rec Table(CompanyNumber Varchar(5), Account Varchar(29), PeriodEnds SmallDateTime, DocType Varchar(2), DocNumber Decimal(8,0))

	Insert Into		@Out_Ops_Rec
	Select Distinct A.CompanyNumber, A.InventoryAccount, A.PeriodEnds, A.DocType, A.DocNumber
	From			RCardexLedgerCompare2 A
	Inner Join		F4111B B On (ILKCO = CompanyNumber And A.InventoryAccount = B.InventoryAccount And A.PeriodEnds = B.PeriodEnds And ILDCT = DocType And ILDOC = DocNumber And ILDCTO = OrderType)
	Inner Join		F41021 C On (ILITM = LIITM And ILMCU = LIMCU And ILLOCN = LILOCN And ILLOTN = LILOTN)
	Where			LIPBIN <> ''P'' And
					A.CompanyNumber = ILKCO And A.InventoryAccount = B.InventoryAccount And A.PeriodEnds = B.PeriodEnds And 
					A.DocType = ILDCT And A.DocNumber = ILDOC And A.OrderType = ILDCTO And ILDCTO = ''OV''

		--Transaction logging		
	SELECT  @err = @@error, @rowc = (Select Count(*) From @Out_Ops_Rec)
	EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
	IF @err <> 0 GOTO Err_Handler

End



-- JDE Comments
SET @@Process = ''Build purch comment table ... ''
EXEC Update_Server_Log @@Step, @@Process

Declare @Trex_Pur Table(CompanyNumber Varchar(5), Account Varchar(29), PeriodEnds SmallDateTime, DocType Varchar(2), DocNumber Decimal(8,0), TRex Varchar(50))

Insert Into		@Trex_Pur
Select Distinct ILKCO, InventoryAccount, PeriodEnds, ILDCT, ILDOC, RTrim(ILTREX)
From			F4111B
Where			ILDCT In (Select * From @PurchTypes) And ILTREX <> ''''

	--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler





-- Perform purchasing analysis
    DECLARE C1 CURSOR FOR 
	Select DocType From @PurchTypes

    OPEN C1
    FETCH NEXT FROM C1 INTO @DocType
    WHILE 		@@FETCH_STATUS = 0
    BEGIN

    SET @@Process = ''Analyzing Purchasing Variance; '' + @DocType
    EXEC Update_Server_Log @@Step, @@Process

--	Update	RCardexLedgerCompare2
--	Set		Comment = (Select dbo.ufn_Purch_Analysis (CompanyNumber, InventoryAccount, PeriodEnds, DocType, DocNumber, OrderType, CardexLedgerVariance, Status, MatchingDocument))
--	From	RCardexLedgerCompare2
--	Where	DocType = @DocType And Comment = ''''

	-- Direct Ship Mismatch
				Update		RCardexLedgerCompare2
				Set			Comment = ''Direct Ship Mismatch''
				From		RCardexLedgerCompare2 A
				Where		OrderType In (Select Distinct SDRCTO From F42119 Where SDLNTY = ''D'') And A.DocType = @DocType


	-- Outside Operations Receipt not in primary location

				Update		RCardexLedgerCompare2
				Set			Comment = ''Outside Operation receipt not to primary location''
				From		RCardexLedgerCompare2 A
				Inner Join	@Out_Ops_Rec B ON (A.CompanyNumber = B.CompanyNumber And A.InventoryAccount = B.Account And A.PeriodEnds = B.PeriodEnds And A.DocType = B.DocType And A.DocNumber = B.DocNumber)
				Where		A.DocType = @DocType And InventoryAccount = ''Outside Operations''

	-- Voucher Variance in Account
				Update		RCardexLedgerCompare2
				Set			Comment = ''Voucher Variance in Account''
				From		RCardexLedgerCompare2 A
				Where		A.DocType = @DocType And A.DocType <> ''OV'' and Status = ''No Cardex''


	-- Voucher Variance in Cardex
				Update		RCardexLedgerCompare2
				Set			Comment = ''Voucher Variance in Account''
				From		RCardexLedgerCompare2 A
				Where		A.DocType = @DocType And A.DocType <> ''OV'' and Status = ''No GL''


	-- JDE Comments
				Update	RCardexLedgerCompare2
				Set		Comment = Trex
				FROM    RCardexLedgerCompare2 A
				Inner Join @Trex_Pur B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber)
				WHERE   A.DocType = @DocType  And Comment = ''''


		--Transaction logging		
    SELECT  @err = @@error, @rowc = (Select Count(*) From RCardexLedgerCompare2 Where DocType = @DocType and Comment <> '''')
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler

            FETCH NEXT FROM C1 INTO @DocType 
    END

    CLOSE C1
    DEALLOCATE C1

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS








-- Inventory **********************************************************************
--Prep Inventory Tables
SET @@Process = ''Preparing Inventory Data ... ''
EXEC Update_Server_Log @@Step, @@Process

-- Build Inventory Type Table
SET @@Process = ''Building Inv Type table ... ''
EXEC Update_Server_Log @@Step, @@Process

Declare @Inv_Types Table (DocType Varchar(2))
Insert Into @Inv_Types
Select Distinct GLDCT From F0911 Where GLICUT = ''N'' And Exists (Select * From RCardexLedgerCompare2 Where GLDCT = DocType)

	--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler

-- Inventory comments table
SET @@Process = ''Build inv comment table ... ''
EXEC Update_Server_Log @@Step, @@Process
Declare @Trex_Inv Table(CompanyNumber Varchar(5), Account Varchar(29), PeriodEnds SmallDateTime, DocType Varchar(2), DocNumber Decimal(8,0), TRex Varchar(50))

Insert Into		@Trex_Inv
Select Distinct ILKCO, InventoryAccount, PeriodEnds, ILDCT, ILDOC, RTrim(ILTREX)
From			F4111B
Where			ILDCT In (Select * From @Inv_Types) And ILTREX <> ''''

	--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler



-- Perform Inventory Analysis
    DECLARE C1 CURSOR FOR 
	Select * From @Inv_Types

    OPEN C1
    FETCH NEXT FROM C1 INTO @DocType
    WHILE 		@@FETCH_STATUS = 0
    BEGIN

    SET @@Process = ''Analyzing Inventory Variance; '' + @DocType
    EXEC Update_Server_Log @@Step, @@Process

--	Update	RCardexLedgerCompare2
--	Set		Comment = (Select dbo.ufn_Inv_Analysis (CompanyNumber, InventoryAccount, PeriodEnds, DocType, DocNumber, OrderType, CardexLedgerVariance, Status))
--	From	RCardexLedgerCompare2
--	Where	DocType = @DocType And Comment = ''''

	-- Unbalanced stock transfers

				Update		RCardexLedgerCompare2
				Set			Comment = ''Unbalanced quantity in stock transfer''
				FROM		RCardexLedgerCompare2 A
				Inner Join	v_Unbalanced_Stock_Transfers B On (A.DocType = B.DocType And A.DocNumber = B.DocNumber)
				WHERE		A.DocType = @DocType

	-- JDE Comments
				Update	RCardexLedgerCompare2
				Set		Comment = Trex
				FROM    RCardexLedgerCompare2 A
				Inner Join @Trex_Inv B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber)
				WHERE   A.DocType = @DocType  And Comment = ''''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = (Select Count(*) From RCardexLedgerCompare2 Where DocType = @DocType and Comment <> '''')
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0 GOTO Err_Handler

            FETCH NEXT FROM C1 INTO @DocType 
    END

    CLOSE C1
    DEALLOCATE C1

    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS




-- Successful Completion 
DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
SET		@@Process = ''Procedure completed sucessfully''
EXEC 	Update_Server_Log @@Step, @@Process 
    RETURN 0


-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 ) WITH Log
    RETURN -1
--End
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_160_Document_Analysis] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp_170_BaseLine_Processing]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_170_BaseLine_Processing]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp_170_BaseLine_Processing] ( @Err INT OUTPUT )
AS --******************************
-- RapidReconciler Baseline Processing
--******************************

DECLARE @@Step VARCHAR(30), @@Process VARCHAR(100), @rowc INT,  @Check INT, @Company VarChar(5)
SET @@Step = ''170 Baseline Processing''


-- There are 2 Tables in the baseline process
-- RBaseline, a summary table at the company level
-- RBaselinePerpetual, item details for each company


--Clear baseline data if the period cutoff date was changed or baseline perpetual records do not exist
    DECLARE @CompanyNumber VARCHAR(5)
    DECLARE C1 CURSOR FOR	SELECT  CompanyNumber FROM RCompanies WHERE BaselineExist = 0 
							Union 
							Select Distinct CompanyNumber From RCompanies A
								Where Not Exists (Select Distinct CompanyNumber FROM RBaselinePerpetual B WHERE  A.CompanyNumber = B.CompanyNumber)

    SET @@Process = ''Resetting baseline for company '' + @CompanyNumber
    EXEC Update_Server_Log @@Step, @@Process

    OPEN C1
    FETCH NEXT FROM C1 INTO @CompanyNumber
    WHILE @@FETCH_STATUS = 0

BEGIN

			SET @@Process = ''Resetting baseline; Company '' + @CompanyNumber
			EXEC Update_Server_Log @@Step, @@Process

            EXEC	Remove_Baseline_Company @CompanyNumber
            UPDATE  RCompanies
            SET     BaselineExist = 0
            WHERE   CompanyNumber = @CompanyNumber

		--Transaction logging		
			SELECT  @err = @@error, @rowc = @@rowcount
			EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
			IF @err <> 0 GOTO Err_Handler


--Create Baseline Table
            SET @@Process = ''Loading baseline summary; Company '' + @CompanyNumber
            EXEC Update_Server_Log @@Step, @@Process

            INSERT  INTO RBaseline
                    SELECT  CompanyNumber, AL.LongAccount, W.PeriodBegins - 1, 0, 0, 0, 0, 0, LastCompleteRun, W.PeriodCutoff
                    FROM    RInvAccountList AL With (NOLOCK),
                            RTimestamp,
                            ( SELECT    LongAccount, (Select Min(PeriodCutoff) From RCompanies) As PeriodCutoff, MIN(PeriodBegins) AS PeriodBegins
                              FROM      RInvAccountList AL 
                              INNER JOIN RFiscalCalendar C ON ( AL.CompanyNumber = C.CompanyNumber )
                              WHERE     LongAccount NOT IN ( ''GL Class Not in Base Table'', ''Outside Operations'' )
                              GROUP BY  LongAccount ) AS W
                    WHERE   AL.LongAccount = W.LongAccount And CompanyNumber = @CompanyNumber

				--Transaction logging		
            SELECT  @err = @@error, @rowc = @@rowcount
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
            IF @err <> 0 GOTO Err_Handler


			-- Update Amounts
            SET @@Process = ''Calculating cardex amount''
            EXEC Update_Server_Log @@Step, @@Process

            UPDATE  RBaseline
            SET     SumCardex = W.Amount
            FROM    RBaseline,
                    ( SELECT    InventoryAccount, SUM(ILPAID) AS Amount
                      FROM      F4111B CX 
                      INNER JOIN RBaseline BL ON ( BL.LongAccount = CX.InventoryAccount AND CX.PeriodEnds > BL.PeriodEnds ) 
                      INNER JOIN RFiscalCalendar CAL ON ( CX.ILKCO = CAL.CompanyNumber AND  CX.PeriodEnds = CAL.PeriodEnds ) 
                      GROUP BY  InventoryAccount ) AS W
            WHERE   RBaseline.LongAccount = W.InventoryAccount And CompanyNumber = @CompanyNumber

				--Transaction logging		
            SELECT  @err = @@error, @rowc = @@rowcount
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
            IF @err <> 0 GOTO Err_Handler


            SET @@Process = ''Calculating perpetual amount''
            EXEC Update_Server_Log @@Step, @@Process

            UPDATE  RBaseline
            SET     SumPerpetual = W.Amount
            FROM    RBaseline,
                    ( SELECT    PInv.LongAccount, SUM(AmountonHand) AS Amount
                      FROM      RPerpetualInv PInv 
                      INNER JOIN RBaseline BL ON ( BL.LongAccount = PInv.LongAccount ) 
                      GROUP BY  PInv.LongAccount ) AS W
            WHERE   RBaseline.LongAccount = W.LongAccount And CompanyNumber = @CompanyNumber

				--Transaction logging		
            SELECT  @err = @@error, @rowc = @@rowcount
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
            IF @err <> 0 GOTO Err_Handler


            SET @@Process = ''Calculating amount on hand''
            EXEC Update_Server_Log @@Step, @@Process

            UPDATE  RBaseline
            SET     BaselineAOH = SumPerpetual - SumCardex
            FROM    RBaseline BL
            WHERE   CompanyNumber = @CompanyNumber

				--Transaction logging		
            SELECT  @err = @@error, @rowc = @@rowcount
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
            IF @err <> 0 GOTO Err_Handler


            SET @@Process = ''Calculating variance''
            EXEC Update_Server_Log @@Step, @@Process

            UPDATE  RBaseline
            SET     BaselineVar = BaselineAOH - EndingGLBalance
            FROM    RBaseline
			Where	CompanyNumber = @CompanyNumber

				--Transaction logging		
            SELECT  @err = @@error, @rowc = @@rowcount
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
            IF @err <> 0 GOTO Err_Handler



			-- Added 02/08/2007
			-- Round the baseline amounts to the number of decimal places
			-- specified in the constants (extended decimals)


            SET @@Process = ''Rounding extended decimals''
            EXEC Update_Server_Log @@Step, @@Process

            UPDATE  RBaseline
            SET     SumCardex = ROUND(SumCardex, 2),
                    SumPerpetual = ROUND(SumPerpetual, 2),
                    BaselineAOH = ROUND(BaselineAOH, 2),
                    BaselineVAR = ROUND(BaselineVAR, 2)
            FROM    RBaseline A 
			WHERE   CompanyNumber = @CompanyNumber

				--Transaction logging		
            SELECT  @err = @@error, @rowc = @@rowcount
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
            IF @err <> 0 GOTO Err_Handler




--Create Baseline Perpetual Table
      SET @@Process = ''Loading baseline details; Company '' + @CompanyNumber
      EXEC Update_Server_Log @@Step, @@Process

            INSERT  INTO dbo.RBaselinePerpetual
                    SELECT  PInv.CompanyNumber, LongAccount, BranchPlant, ShortItem, ItemNumber, Location, Lot,
                            AmountonHand, AmountinCardex, QuantityonHand, QuantityinCardex, 
							Unitofmeasure, LastUpdate, CardexUpdate, DocType, DocNumber, DocAmount, 6
                    FROM    dbo.RPerpetualInv PInv 
					Where CompanyNumber = @CompanyNumber

		--Transaction logging		
            SELECT  @err = @@error, @rowc = @@rowcount
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
            IF @err <> 0 GOTO Err_Handler

            FETCH NEXT FROM C1 INTO @CompanyNumber
        END

    CLOSE C1
    DEALLOCATE C1


-- Add new baseline records for new items added
-- Fixing Long item numbers where they were changed in the item master
    SET @@Process = ''Fixing long item if item master changed''
    EXEC Update_Server_Log @@Step, @@Process

	Update RBaselinePerpetual
	Set ItemNumber = IMLITM
	From RBaselinePerpetual
	Inner Join vcr_F4101 On (ShortItem = IMITM)
	Where ItemNumber <> IMLITM

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


-- This catches any items added to perpetual after the initial baaseline was established.

    SET @@Process = ''Adding baseline details for new items''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RBaselinePerpetual
            SELECT  A.CompanyNumber, A.LongAccount, A.BranchPlant, A.ShortItem, A.ItemNumber, A.Location, A.Lot,
                    0, 0, 0, 0, UnitofMeasure, 0, 0, '''', 0, 0, 8
            FROM    RPerpetualInv A 
            WHERE   NOT EXISTS ( SELECT *
                                 FROM   RBaselinePerpetual B
                                 WHERE  A.CompanyNumber = B.CompanyNumber AND A.LongAccount = B.LongAccount AND
                                        A.BranchPlant = B.BranchPlant AND A.ShortItem = B.ShortItem AND
                                        A.Location = B.Location AND A.Lot = B.Lot )

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler



-- Update baseline flag
    SET @@Process = ''Flag companies where baseline has been calculated''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RCompanies
    SET     BaselineExist = 1
    FROM    RCompanies A 
    WHERE   BaselineExist = 0 AND Exists (Select Distinct CompanyNumber From RBaselinePerpetual T Where A.CompanyNumber = T.CompanyNumber)

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler



-- Update Variance Amounts in Perpetual Table
    SET @@Process = ''Updating variance amounts in perpetual table''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RPerpetualInv
    SET     BaselineQOH = B.QuantityonHand,
            BaselineAOH = B.AmountonHand,
            EstUnits = ( A.QuantityinCardex - B.QuantityinCardex ) - ( A.QuantityonHand - B.QuantityonHand ),
            BaselineVar = ( A.AmountinCardex - B.AmountinCardex ) - ( A.AmountonHand - B.AmountonHand )
    FROM    RPerpetualInv A 
    INNER JOIN RBaselinePerpetual B
            ON ( A.CompanyNumber = B.CompanyNumber AND
                 A.LongAccount = B.LongAccount AND
                 A.BranchPlant = B.BranchPlant AND
                 A.ShortItem = B.ShortItem AND
                 A.Location = B.Location AND
                 A.Lot = B.Lot )

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler



/* Updating the latest date in the perpetual table.
This supports the item roll integrity dialog */



-- Update Transaction date in Perpetual Table
    SET @@Process = ''Last trans date in perpetual table''
    EXEC Update_Server_Log @@Step, @@Process

Update		RPerpetualInv
Set			LastRec = B.MaxDate
From		RPerpetualInv A, 
			(Select	ILKCO As CompanyNumber, 
			ILMCU As BranchPlant, 
			ILITM As ShortItem, 
			ILLOCN As Location, 
			ILLOTN As Lot, 
			MAX(ILTRDJ) As MaxDate
			From F4111B	
			Group By	ILKCO, 
						ILMCU, 
						ILITM, 
						ILLOCN, 
						ILLOTN) As B
Where		A.CompanyNumber = B.CompanyNumber And A.BranchPlant = B.BranchPlant And A.ShortItem = B.ShortItem And A.Location = B.Location And A.Lot = B.Lot And
			(ABS(A.BaselineVar) > 0 Or ABS(A.EstUnits)>0)


		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler

SET @@Process = ''Updating from F41021 if greater CM<>02''
EXEC Update_Server_Log @@Step, @@Process


Update		RPerpetualInv
Set			LastRec = B.MaxDate
From		RPerpetualInv A, 
			(Select		LIMCU As BranchPlant, 
			LIITM As ShortItem, 
			LILCON As Location, 
			LILOTN As Lot, 
			MAX(LIUPMJ) As MaxDate
			From vt_F41021
			Where LIITM > 0		
			Group By	LIMCU, 
						LIITM, 
						LILCON, 
						LILOTN) As B
Where		CostMethod <> ''02'' And A.BranchPlant = B.BranchPlant And A.ShortItem = B.ShortItem And A.Location = B.Location And A.Lot = B.Lot And
			(ABS(A.BaselineVar) > 0 Or ABS(A.EstUnits)>0) And B.MaxDate > LastRec


		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler
    
    
SET @@Process = ''Updating from F41021 if greater CM=02''
EXEC Update_Server_Log @@Step, @@Process


Update		RPerpetualInv
Set			LastRec = B.MaxDate
From		RPerpetualInv A, 
			(Select	LIMCU As BranchPlant, 
			LIITM As ShortItem, 
			MAX(LIUPMJ) As MaxDate
			From vt_F41021
			Where LIITM > 0	
			Group By LIMCU, LIITM) As B
Where		CostMethod = ''02'' And A.BranchPlant = B.BranchPlant And A.ShortItem = B.ShortItem And
			(ABS(A.BaselineVar) > 0 Or ABS(A.EstUnits)>0)And B.MaxDate > LastRec


		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler



-- Reset quantity variances on the second cycle only
-- Need to do this in the event the initial balance forward is captured while transactions are being processed.

Update RSystemVariables 
Set Value = Cast(Cast(Value As Int) + 1 As Varchar (100)) 
From RSystemVariables 
Where Name = ''RefreshCount''

--If (Select Cast(Value As Int) 
--From RSystemVariables 
--Where Name = ''RefreshCount'') = 2
--Begin
--Exec dbo.usp3_reset_item_roll @Err Output
--End



-- Successful Completion
DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
SET		@@Process = ''Procedure completed sucessfully''
EXEC 	Update_Server_Log @@Step, @@Process  
    RETURN 0


-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 )
    RETURN -1
--End
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_170_BaseLine_Processing] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp_180_Account_Summary]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_180_Account_Summary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp_180_Account_Summary] ( @Err INT OUTPUT )
AS 
    DECLARE @@Step VARCHAR(30),  @@Process VARCHAR(100),  @rowc INT, @check2 INT,  @check3 INT,  @Company VARCHAR(5), @datavalidation Float
    SET @@Step = ''180 Account Summary''


    TRUNCATE TABLE 	RInvAccountSummary


-- ************************** GL Entries     *************************
--Insert Baseline Records into Account Summary Table
    SET @@Process = ''Adding baseline records to account summary table''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RInvAccountSummary
            SELECT  BL.CompanyNumber,
                    BL.LongAccount,
                    0,
                    BL.PeriodEnds,
                    0,
                    0,
                    BL.EndingGLBalance,
                    ''Baseline'',
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    BL.BaselineAOH,
                    BL.EndingGLBalance - BL.BaselineAOH,
                    0,
                    0,
                    BL.EndingGLBalance - BL.BaselineAOH,
                    BL.CaptureDate,
                    0,0
            FROM    RBaseline BL 
            INNER JOIN RInvAccountList AL
                    ON ( BL.LongAccount = AL.LongAccount )

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


-- Insert Accounts, Periods and Balances
    SET @@Process = ''Adding accounts and periods''
    EXEC Update_Server_Log @@Step, @@Process
 

    INSERT  INTO RInvAccountSummary
            SELECT  AC.CompanyNumber,
                    AC.LongAccount,
                    CAL.PeriodBegins,
                    CAL.PeriodEnds,
                    0 AS BeginningBalance,
                    0 AS PeriodGL,
                    0 AS EndingGLBalance,
                    ''End'' AS GLRollOK,
                    0 AS UnpostedBatchAmount,
                    0 AS PeriodCardex,
                    0 AS PCAR,
                    0 AS PeriodUnpostedCardex,
                    0 AS UCAR,
                    0 AS PBAL,
                    0 AS AOH,
                    0 AS AVAR,
                    0 AS TVAR,
                    0 AS JRNL,
                    0 AS AOOB,
                    ''End'',
                    0,0
            FROM    dbo.RInvAccountList AC 
            INNER JOIN dbo.RFiscalCalendar CAL
                    ON ( AC.CompanyNumber = CAL.CompanyNumber )
            ORDER BY AC.CompanyNumber,
                    AC.LongAccount,
                    CAL.PeriodEnds

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


--Load Beginning Balances
    SET @@Process = ''Adding beginning GL balances''
    EXEC Update_Server_Log @@Step, @@Process
 
    UPDATE  RInvAccountSummary
    SET     BeginningBalance = BAL.BeginningBalance
    FROM    RInvAccountSummary AC 
    INNER JOIN dbo.RBegGLBalances BAL
            ON ( BAL.CompanyNumber = AC.CompanyNumber AND
                 BAL.LongAccount = AC.LongAccount AND
                 BAL.PeriodEnds = AC.PeriodEnds )

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


--Calculate GL Period Activity
    SET @@Process = ''Adding GL activity by period''
    EXEC Update_Server_Log @@Step, @@Process
 
    UPDATE  RInvAccountSummary
    SET     PeriodGL = M.GLAA
    FROM    RInvAccountSummary T,
            dbo.RConstants CONST,
            ( SELECT    CompanyNumber,
                        InventoryAccount,
                        PeriodEnds,
                        SUM(LedgerAmount) AS GLAA
              FROM      RCardexLedgerCompare
              GROUP BY  CompanyNumber,
                        InventoryAccount,
                        PeriodEnds ) AS M
    WHERE   T.CompanyNumber = M.CompanyNumber AND
            M.InventoryAccount = T.LongAccount AND
            T.PeriodEnds = M.PeriodEnds

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


--Calculate Ending GL Balance
    SET @@Process = ''Calculating ending GL balances''
    EXEC Update_Server_Log @@Step, @@Process
 
    UPDATE  RInvAccountSummary
    SET     EndingGLBalance = BeginningBalance + PeriodGL
    FROM    RInvAccountSummary

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


--If the fiscal year rolls forward calculate the beginning balance for period 1 of the new year
    SET @@Process = ''Adjusting for new fiscal year if year end process not completed''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RInvAccountSummary
    SET     BeginningBalance = AS2.EndingGLBalance + AS2.UnpostedBatchAmount,
            GLRollOK = ''End*''
    FROM    dbo.RInvAccountSummary 
    INNER JOIN dbo.RFiscalCalendar FC
            ON ( dbo.RInvAccountSummary.CompanyNumber = FC.CompanyNumber AND
                 dbo.RInvAccountSummary.PeriodEnds = FC.PeriodEnds ) 
    INNER JOIN dbo.RInvAccountSummary AS2
            ON ( dbo.RInvAccountSummary.CompanyNumber = AS2.CompanyNumber AND
                 dbo.RInvAccountSummary.LongAccount = AS2.LongAccount ) 
    INNER JOIN dbo.RFiscalCalendar FC2
            ON ( AS2.CompanyNumber = FC2.CompanyNumber AND
                 AS2.PeriodEnds = FC2.PeriodEnds )
    WHERE   ( FC.FiscalYear - FC2.FiscalYear = 1 ) AND
            CONVERT(INT, dbo.RInvAccountSummary.PeriodEnds) - CONVERT(INT, AS2.PeriodEnds) < 40 AND
            dbo.RInvAccountSummary.BeginningBalance = 0

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err


-- Calculate ending balances for adjusted fiscal year
    SET @@Process = ''Calculating ending GL balance for adjusted fiscal year''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RInvAccountSummary
    SET     EndingGLBalance = dbo.RInvAccountSummary.BeginningBalance + dbo.RInvAccountSummary.PeriodGL
    FROM    dbo.RInvAccountSummary
    WHERE   GLRollOK = ''End*''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


--Calculate Unposted Batch Amount
    SET @@Process = ''Adding unposted batch amounts''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     UnpostedBatchAmount = T.GLAA
    FROM    RInvAccountSummary F,
            ( SELECT    GLCO,
                        GLANI,
                        PeriodEnds,
                        SUM(GLAA) AS GLAA
              FROM      dbo.F0911
              WHERE     GLPOST <> ''P''
              GROUP BY  GLCO,
                        GLANI,
                        PeriodEnds ) AS T
    WHERE   T.GLCO = F.CompanyNumber AND
            T.GLANI = F.LongAccount AND
            T.PeriodEnds = F.PeriodEnds

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


--Calculate Roll Forward Status
    SET @@Process = ''Calculating roll forward status yes for GL''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     GLRollOK = ''Yes''
    FROM    RInvAccountSummary 
    INNER JOIN RInvAccountSummary AS2
            ON ( RInvAccountSummary.CompanyNumber = AS2.CompanyNumber AND
                 RInvAccountSummary.LongAccount = AS2.LongAccount )
    WHERE   RInvAccountSummary.PeriodEnds + 1 = AS2.PeriodBegins AND
            RInvAccountSummary.EndingGLBalance = AS2.BeginningBalance AND
            RInvAccountSummary.GLRollOK <> ''Baseline''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


-- Identify GL accounts that do not roll forward
    SET @@Process = ''Calculating roll forward status no for GL''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     GLRollOK = ''No''
    FROM    RInvAccountSummary 
    INNER JOIN RInvAccountSummary AS2
            ON ( RInvAccountSummary.CompanyNumber = AS2.CompanyNumber AND
                 RInvAccountSummary.LongAccount = AS2.LongAccount )
    WHERE   RInvAccountSummary.PeriodEnds + 1 = AS2.PeriodBegins AND
            RInvAccountSummary.EndingGLBalance <> AS2.BeginningBalance AND
            RInvAccountSummary.GLRollOK <> ''Baseline''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


		--Add warning message if there are roll forward problems
    IF @rowc > 0 
        BEGIN
            SET @err = 60000
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        END


--Calculate Ending GL Balance for Baseline Record
    SET @@Process = ''Calcualting ending gl balance for baseline''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     EndingGLBalance = As2.BeginningBalance
    FROM    RInvAccountSummary 
    INNER JOIN RInvAccountSummary AS2
            ON ( RInvAccountSummary.CompanyNumber = AS2.CompanyNumber AND
                 RInvAccountSummary.LongAccount = AS2.LongAccount )
    WHERE   RInvAccountSummary.PeriodEnds + 1 = AS2.PeriodBegins AND
            RInvAccountSummary.GLRollOK = ''Baseline''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler



-- ****************** Cardex Entries ********************************
--Calculate Period Cardex Amount
    SET @@Process = ''Adding period cardex activity''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RInvAccountSummary
    SET     PeriodCardex = CX.ILPAID --, PostedCardexAmount = CX.ILPAID
    FROM    RInvAccountSummary T,
            ( SELECT    InventoryAccount,
                        PeriodEnds,
                        SUM(CardexAmount) AS ILPAID
              FROM      RCardexLedgerCompare
              WHERE     Status NOT IN ( ''Manual Entry'',
                                        ''Sales Update Required'',
                                        ''Mfg Accounting Required'' )
              GROUP BY  InventoryAccount,
                        PeriodEnds ) AS CX
    WHERE   CX.InventoryAccount = T.LongAccount AND
            CX.PeriodEnds = T.PeriodEnds

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler



--Calculate Period UnPosted Cardex Amount
    SET @@Process = ''Adding unposted cardex amounts''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     UnpostedCardexAmount = M.ILPAID,
            PeriodUnpostedCardex = M.ILPAID
    FROM    RInvAccountSummary T,
            ( SELECT    InventoryAccount,
                        PeriodEnds,
                        SUM(CardexAmount) AS ILPAID
              FROM      dbo.RCardexLedgerCompare
              WHERE     Status IN ( ''Sales Update Required'',
                                    ''Mfg Accounting Required'' )
              GROUP BY  InventoryAccount,
                        PeriodEnds ) AS M
    WHERE   M.InventoryAccount = T.LongAccount AND
            M.PeriodEnds = T.PeriodEnds

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler



--Calculate the Amount on Hand In Account Summary
    SET @@Process = ''Adding amount on hand''
    EXEC Update_Server_Log @@Step, @@Process
 
    UPDATE  RInvAccountSummary
    SET     AmountOnHand = P.AOH
    FROM    RInvAccountSummary T,
            ( SELECT    LongAccount,
                        SUM(AmountOnHand) AS AOH
              FROM      RPerpetualInv
              GROUP BY  LongAccount ) AS P
    WHERE   T.LongAccount = P.LongAccount

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler



--Roll Forward the On Hand amounts
    SET @@Process = ''Rolling forward on hand amounts''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     AmountonHand = T.Amount
    FROM    RInvAccountSummary A,
            ( SELECT    X.LongAccount,
                        X.PeriodEnds,
                        W.BaselineAOH + SUM(W.Amount) AS Amount
              FROM      RInvAccountSummary X,
                        ( SELECT    B.LongAccount,
                                    B.PeriodEnds,
                                    BaselineAOH,
                                    SUM(PeriodCardex + PeriodUnPostedCardex) AS Amount
                          FROM      RInvAccountSummary B 
                          INNER JOIN RBaseline BL
                                    ON ( B.LongAccount = BL.LongAccount )
                          GROUP BY  B.LongAccount,
                                    B.PeriodEnds,
                                    BaselineAOH ) AS W
              WHERE     X.LongAccount = W.LongAccount AND
                        W.PeriodEnds <= X.PeriodEnds
              GROUP BY  X.LongAccount,
                        X.PeriodEnds,
                        W.BaselineAOH ) AS T
    WHERE   A.LongAccount = T.LongAccount AND
            A.PeriodEnds = T.PeriodEnds

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


--Calculate Item Balance/Cardex Variance
    SET @@Process = ''Adding item balance/cardex variance''
    EXEC Update_Server_Log @@Step, @@Process
 

    UPDATE  RInvAccountSummary
    SET     BalCXVar = W.Amount
    FROM    RInvAccountSummary A,
            ( SELECT    LongAccount,
                        SUM(BaselineVar) AS Amount
              FROM      RPerpetualInv
              WHERE     LongAccount NOT IN ( ''GL Class Not in Base Table'', ''Outside Operations'' )
              GROUP BY  LongAccount ) AS W
    WHERE   A.LongAccount = W.LongAccount AND
            GLRollOK LIKE ''End%''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler



-- ************* Variance Calculations ***************************************

--Calculate the Account Variance
    SET @@Process = ''Calculating baseline variances''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     AccountVariance = ( EndingGLBalance - AmountonHand ),
            OutofBalance = ( EndingGLBalance - AmountonHand )
    FROM    RInvAccountSummary
    WHERE   GLRollOK = ''Baseline''

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler


    SET @@Process = ''Calculating account variance''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     AccountVariance = ( BeginningBalance + PeriodCardex + PeriodUnpostedCardex - AmountonHand )
    FROM    RInvAccountSummary
    WHERE   GLRollOK <> ''Baseline''

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler



--Calculate the Transacton Variance
    SET @@Process = ''Calculating transaction variance''
    EXEC Update_Server_Log @@Step, @@Process
 
    UPDATE  RInvAccountSummary
    SET     TransactionVariance = G.Variance
    FROM    RInvAccountSummary T,
            ( SELECT    InventoryAccount,
                        PeriodEnds,
                        SUM(CardexLedgerVariance) AS Variance
              FROM      RCardexLedgerCompare
              WHERE     Status NOT IN ( ''Sales Update Required'',
                                        ''Mfg Accounting Required'',
                                        ''Manual Entry'' )
              GROUP BY  InventoryAccount,
                        PeriodEnds ) AS G
    WHERE   G.InventoryAccount = T.LongAccount AND
            G.PeriodEnds = T.PeriodEnds

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler




--Calculate Manual Journal Entries
    SET @@Process = ''Calculating manual journal entries''
    EXEC Update_Server_Log @@Step, @@Process
 
    UPDATE  RInvAccountSummary
    SET     JournalEntries = G.JE
    FROM    RInvAccountSummary T,
            ( SELECT    CompanyNumber,
                        InventoryAccount,
                        PeriodEnds,
                        SUM(CardexLedgerVariance) AS JE
              FROM      RCardexLedgerCompare
              WHERE     Status = ''Manual Entry''
              GROUP BY  CompanyNumber,
                        InventoryAccount,
                        PeriodEnds ) AS G
    WHERE   G.CompanyNumber = T.CompanyNumber AND
            G.InventoryAccount = T.LongAccount AND
            G.PeriodEnds = T.PeriodEnds

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler

--Get End GL Balance for current period
    SET @@Process = ''Calculate end GL balance for current period''
    EXEC Update_Server_Log @@Step, @@Process

	Update	RInvAccountSummary
	Set		EndingGLBalance = EndingGLBalance + UnpostedBatchAmount
	From	RInvAccountSummary
	Where	GLRollOK Like ''End%''

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler


--Calculate Total Out of Balance in Account Summary
    SET @@Process = ''Calculating out of balance''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
	Set		OutOfBalance = EndingGLBalance - AmountOnHand  + BalCXVar
    FROM    RInvAccountSummary
    WHERE   GLRollOK <> ''Baseline''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


--Calculate Roll Forward Status in Account Summary for Inv
    SET @@Process = ''Calculating inventory roll forward status yes for inv''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     OOBRollOK = ''Yes''
    FROM    RInvAccountSummary 
    INNER JOIN RInvAccountSummary AS2
            ON ( RInvAccountSummary.CompanyNumber = AS2.CompanyNumber AND
                 RInvAccountSummary.LongAccount = AS2.LongAccount )
    WHERE   RInvAccountSummary.PeriodEnds + 1 = AS2.PeriodBegins AND
            RInvAccountSummary.OutofBalance = AS2.AccountVariance AND
            RInvAccountSummary.GLRollOK <> ''Baseline''

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler


    SET @@Process = ''Calculating inventory roll forward status no for inv''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     OOBRollOK = ''No''
    FROM    RInvAccountSummary 
    INNER JOIN RInvAccountSummary AS2
            ON ( RInvAccountSummary.CompanyNumber = AS2.CompanyNumber AND
                 RInvAccountSummary.LongAccount = AS2.LongAccount )
    WHERE   RInvAccountSummary.PeriodEnds + 1 = AS2.PeriodBegins AND
            RInvAccountSummary.OutofBalance <> AS2.AccountVariance AND
            RInvAccountSummary.GLRollOK <> ''Baseline''

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler



--Update Account Summary with Timestamp
    SET @@Process = ''Updating last run date''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     OOBRollOK = ''End'' + '' - '' + RTimestamp.LastCompleteRun
    FROM    RInvAccountSummary 
    INNER JOIN RTimeStamp
            ON ( 1 = 1 )
    WHERE   OOBRollOK = ''End''

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler






-- Account List Updates *************************************************
--GL and Inventory Summary Variances
	--Get ''From Date'' from constants
    SET @@Process = ''Get the From date''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountList
    SET     From_Date = Comp.PeriodCutoff
    FROM    RInvAccountList AL 
    INNER JOIN RCompanies Comp
            ON ( AL.CompanyNumber = Comp.CompanyNumber )

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler


	--Get To Date From Account Summary
    SET @@Process = ''Get the To date''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountList
    SET     To_Date = ASum.PeriodEnds
    FROM    RInvAccountList AL,
            ( SELECT    CompanyNumber,
                        LongAccount,
                        MAX(PeriodEnds) AS PeriodEnds
              FROM      RInvAccountSummary
              WHERE     GLRollOK NOT LIKE ''End%''
              GROUP BY  CompanyNumber,
                        LongAccount ) AS ASum
    WHERE   AL.CompanyNumber = ASum.CompanyNumber AND
            AL.LongAccount = ASum.LongAccount

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler



--Get Beginning Balance from Account Summary
    SET @@Process = ''Calculate beginning balances''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountList
    SET     Beginning_Balance = ASum.BeginningBalance,
            Beginning_Balance_I = ASum.AmountonHand - ( ASum.PeriodCardex + ASum.PeriodUnpostedCardex )
    FROM    RInvAccountList AL,
            ( SELECT    A.CompanyNumber,
                        A.LongAccount,
                        A.BeginningBalance,
                        A.AmountonHand,
                        A.PeriodCardex,
                        A.PeriodUnpostedCardex
              FROM      RInvAccountSummary A,
                        ( SELECT    CompanyNumber,
                                    LongAccount,
                                    MIN(PeriodEnds) AS PeriodEnds
                          FROM      RInvAccountSummary
                          WHERE     GLRollOK NOT LIKE ''Baseline%''
                          GROUP BY  CompanyNumber,
                                    LongAccount ) AS T
              WHERE     A.CompanyNumber = T.CompanyNumber AND
                        A.LongAccount = T.LongAccount AND
                        A.PeriodEnds = T.PeriodEnds ) AS ASum
    WHERE   AL.CompanyNumber = ASum.CompanyNumber AND
            AL.LongAccount = ASum.LongAccount

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler




--Update GL Details in Account List
    SET @@Process = ''Calculate sum details''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountList
    SET     Sum_Details = ASum.PeriodGL,
            Unposted_Batches = ASum.UnpostedBatches,
            Sum_Details_I = ASum.PeriodCX,
            Unposted_Cardex = ASum.UnpostedCX
    FROM    RInvAccountList AL,
            ( SELECT    CompanyNumber,
                        LongAccount,
                        SUM(PeriodGL) AS PeriodGL,
                        SUM(UnpostedBatchAmount) AS UnpostedBatches,
                        SUM(PeriodCardex) AS PeriodCX,
                        SUM(PeriodUnpostedCardex) AS UnpostedCX
              FROM      RInvAccountSummary
              WHERE     GLRollOK NOT LIKE ''End%''
              GROUP BY  CompanyNumber,
                        LongAccount ) AS ASum
    WHERE   AL.CompanyNumber = ASum.CompanyNumber AND
            AL.LongAccount = ASum.LongAccount

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler


-- Calculate Ending Balance in Account List
    SET @@Process = ''Calculate ending balance''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountList
    SET     Calculated_End_Bal = Beginning_Balance + Sum_Details,
            Calculated_End_Bal_I = Beginning_Balance_I + Sum_Details_I
    FROM    RInvAccountList

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler


--Update Actual End Balance in Account List
    SET @@Process = ''Calculate actual ending balance''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountList
    SET     Actual_End_Bal = ASum.BeginningBalance,
            Actual_End_Bal_I = ASum.AmountonHand - ( PeriodCardex + PeriodUnpostedCardex )
    FROM    RInvAccountList AL 
    INNER JOIN RInvAccountSummary ASum
            ON ( AL.CompanyNumber = ASum.CompanyNumber AND
                 AL.LongAccount = ASum.LongAccount )
    WHERE   GLRollOK LIKE ''End%''

			--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler


-- Calculate Variance in Account List
    SET @@Process = ''Calculate variance''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountList
    SET     Variance = Calculated_End_Bal - Actual_End_Bal,
            Variance_I = Calculated_End_Bal_I - Actual_End_Bal_I
    FROM    RInvAccountList

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler

-- Calculate Unposted Variance in Account List
    SET @@Process = ''Calculate posted variance''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountList
    SET     Posted_Variance = Variance - Unposted_Batches,
            Posted_Variance_I = Variance_I + Unposted_Cardex
    FROM    RInvAccountList

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler




-- *************** Unassigned Account ***********************
--Remove from Account Summary And Account List
    DELETE  RInvAccountSummary
    FROM    RInvAccountSummary
    WHERE   LongAccount = ''GL Class Not in Base Table''


    DELETE  RInvAccountList
    FROM    RInvAccountList
    WHERE   LongAccount = ''GL Class Not in Base Table''



    DECLARE C2 CURSOR
        FOR SELECT  CompanyNumber
            FROM    RCompanies

    OPEN C2
    FETCH NEXT FROM C2 INTO @Company
    WHILE 		@@FETCH_STATUS = 0
        BEGIN


            SET @Check2 = ( SELECT  COUNT(*)
                            FROM    F4111B
                            WHERE   InventoryAccount = ''GL Class Not in Base Table'' AND
                                    ILKCO = @Company )
            SET @Check3 = ( SELECT  COUNT(*)
                            FROM    RPerpetualInv
                            WHERE   LongAccount = ''GL Class Not in Base Table'' AND
                                    CompanyNumber = @Company )

            IF @Check2 + @Check3 > 0 
                BEGIN


--Insert Unassigned Inventory Account into Account List
                    SET @@Process = ''Adding unassigned account to account list for company '' + @Company
                    EXEC Update_Server_Log @@Step, @@Process

                    INSERT  INTO RInvAccountList
                    VALUES  (
                              @Company,
                              ''YYYYYYYY'',
                              '''',
                              '''',
                              '''',
                              ''GL Class Not in Base Table'',
                              '''',
                              0,
                              0,
                              0,
                              0,
                              0,
                              0,
                              0,
                              0,
                              0,
                              0,
                              0,
                              0,
                              0,
                              0,
                              0,
                              0)


		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler






--Insert Unassigned Inventory Account in Account Summary Table
                    SET @@Process = ''Adding unassigned account to summary for company '' + @Company
                    EXEC Update_Server_Log @@Step, @@Process

                    INSERT  INTO RInvAccountSummary
                            SELECT  A.CompanyNumber,
                                    A.LongAccount,
                                    0,
                                    B.MaxPeriodEnds,
                                    0,
                                    0,
                                    0,
                                    ''End'',
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    ''End'',
                                    0,0
                            FROM    RInvAccountList A 
                            INNER JOIN RCompanies B ON ( A.CompanyNumber = B.CompanyNumber )
                            WHERE   LongAccount = ''GL Class Not in Base Table'' AND A.CompanyNumber = @Company


		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler

                END

            FETCH NEXT FROM C2 INTO @Company
        END

    CLOSE C2
    DEALLOCATE C2



    SET @@Process = ''Calculating unassigned current amount on hand''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     AmountonHand = W.Amount, EndingGLBalance = W.Amount
    FROM    RInvAccountSummary A,
            ( SELECT    CompanyNumber,
                        LongAccount,
                        SUM(AmountonHand) AS Amount
              FROM      RPerpetualInv
              WHERE     LongAccount = ''GL Class Not in Base Table''
              GROUP BY  CompanyNumber,
                        LongAccount ) AS W
    WHERE   A.CompanyNumber = W.CompanyNumber AND A.LongAccount = W.LongAccount And GLRollOK Like ''End%''

		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler


--Update unassigned account  transaction variance
-- Current Period Only
    SET @@Process = ''Calculating unassigned transaction variance'' 
    EXEC Update_Server_Log @@Step, @@Process


    UPDATE  RInvAccountSummary
    SET     TransactionVariance = W.Amount * -1, PeriodCardex = W.Amount
    FROM    RInvAccountSummary A,
            ( SELECT    CompanyNumber,
                        InventoryAccount,
                        SUM(CardexAmount) AS Amount
              FROM      RCardexLedgerCompare
              WHERE     InventoryAccount = ''GL Class Not In Base Table''
              GROUP BY  CompanyNumber, InventoryAccount ) AS W
    WHERE   A.CompanyNumber = W.CompanyNumber AND A.LongAccount = W.InventoryAccount And GLRollOK Like ''End%''

		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler




    SET @@Process = ''Calculating beginning variance'' 
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     AccountVariance =  EndingGLBalance - AmountonHand
    FROM    RInvAccountSummary
    WHERE   LongAccount = ''GL Class Not In Base Table''

		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler


    SET @@Process = ''Calculating unassigned item roll forward''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     BalCXVar = W.Amount
    FROM    RInvAccountSummary A,
            ( SELECT    CompanyNumber,
                        LongAccount,
                        SUM(BaselineVar) AS Amount
              FROM      RPerpetualInv
              WHERE     LongAccount = ''GL Class Not in Base Table''
              GROUP BY  CompanyNumber,
                        LongAccount ) AS W
    WHERE   A.CompanyNumber = W.CompanyNumber AND A.LongAccount = W.LongAccount And GLRollOK Like ''End%''

		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler




--Calculate Total Out of Balance
    SET @@Process = ''Calculating unassigned out of balance''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     OutofBalance = (EndingGLBalance - AmountOnHand)
    FROM    RInvAccountSummary
    WHERE   LongAccount = ''GL Class Not In Base Table''

		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler










-- *************** Outside Operations Account ************************************
--Remove from Account Summary And Account List
    DELETE  RInvAccountSummary
    FROM    RInvAccountSummary
    WHERE   LongAccount = ''Outside Operations''

    DELETE  RInvAccountList
    FROM    RInvAccountList
    WHERE   LongAccount = ''Outside Operations''


    DECLARE C2 CURSOR
        FOR SELECT  CompanyNumber
            FROM    RCompanies

    OPEN C2

    FETCH NEXT FROM C2 INTO @Company
    WHILE 		@@FETCH_STATUS = 0
        BEGIN


            SET @Check2 = ( SELECT  COUNT(*)
                            FROM    F4111B
                            WHERE   InventoryAccount = ''Outside Operations'' AND
                                    ILKCO = @Company )
            SET @Check3 = ( SELECT  COUNT(*)
                            FROM    RPerpetualInv
                            WHERE   LongAccount = ''Outside Operations'' AND
                                    CompanyNumber = @Company )
            IF @Check2 + @Check3 > 0 
                BEGIN



--Insert Outside Operations Account into Account List
                    SET @@Process = ''Adding outside operations to account list for company '' + @Company
                    EXEC Update_Server_Log @@Step, @@Process

                    INSERT  INTO RInvAccountList
                            SELECT DISTINCT
                                    @Company,
                                    ''XXXXXXXX'',
                                    '''',
                                    '''',
                                    '''',
                                    ''Outside Operations'',
                                    '''',
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0

		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler




--Insert Outside Operations Account in Account Summary Table
                    SET @@Process = ''Adding outside operations to account summary for company '' + @Company
                    EXEC Update_Server_Log @@Step, @@Process

                    INSERT  INTO RInvAccountSummary
                            SELECT  A.CompanyNumber,
                                    A.LongAccount,
                                    0,
                                    B.MaxPeriodEnds,
                                    0,
                                    0,
                                    0,
                                    ''End'',
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    ''End'',
                                    0,0
                            FROM    RInvAccountList A 
                            INNER JOIN RCompanies B
                                    ON ( A.CompanyNumber = B.CompanyNumber )
                            WHERE   LongAccount = ''Outside Operations'' AND
                                    A.CompanyNumber = @Company

		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler

        END

            FETCH NEXT FROM C2 INTO @Company
        END


    CLOSE C2
    DEALLOCATE C2


--Update Outside Operations Current Amount on Hand
    SET @@Process = ''Calculating outside operations current AOH''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     AmountonHand = W.Amount, EndingGLBalance = W.Amount
    FROM    RInvAccountSummary A,
            ( SELECT    CompanyNumber,
                        LongAccount,
                        SUM(AmountonHand) AS Amount
              FROM      RPerpetualInv
              WHERE     LongAccount = ''Outside Operations''
              GROUP BY  CompanyNumber,
                        LongAccount ) AS W
    WHERE   A.CompanyNumber = W.CompanyNumber AND A.LongAccount = W.LongAccount And GLRollOK Like ''End%''

		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler



--Update Outside Operations  Transaction Variance ***********************************
--Current Period Only

    SET @@Process = ''Calculating outside ops transaction variance'' 
    EXEC Update_Server_Log @@Step, @@Process


    UPDATE  RInvAccountSummary
    SET     TransactionVariance = W.Amount * -1, PeriodCardex = W.Amount
    FROM    RInvAccountSummary A,
            ( SELECT    CompanyNumber,
                        InventoryAccount,
                        SUM(CardexAmount) AS Amount
              FROM      RCardexLedgerCompare2
              WHERE     InventoryAccount = ''Outside Operations''
              GROUP BY  CompanyNumber, InventoryAccount ) AS W
    WHERE   A.CompanyNumber = W.CompanyNumber AND A.LongAccount = W.InventoryAccount And GLRollOK Like ''End%''

		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler




--Calculate the Beginning Variance ***************************************************

    SET @@Process = ''Calculating outside ops BegVar''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     AccountVariance =  EndingGLBalance - AmountonHand
    FROM    RInvAccountSummary
    WHERE   LongAccount = ''Outside Operations''

		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler



    SET @@Process = ''Calculating outside ops item roll forward''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     BalCXVar = W.Amount
    FROM    RInvAccountSummary A,
            ( SELECT    CompanyNumber,
                        LongAccount,
                        SUM(BaselineVar) AS Amount
              FROM      RPerpetualInv
              WHERE     LongAccount = ''Outside Operations''
              GROUP BY  CompanyNumber,
                        LongAccount ) AS W
    WHERE   A.CompanyNumber = W.CompanyNumber AND A.LongAccount = W.LongAccount And GLRollOK Like ''End%''


		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler



--Calculate Total Out of Balance
    SET @@Process = ''Calculating outside ops out of balance''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAccountSummary
    SET     OutofBalance = EndingGLBalance - AmountOnHand
    FROM    RInvAccountSummary
    WHERE   LongAccount = ''Outside Operations''

		--Transaction logging		
        SELECT  @err = @@error, @rowc = @@rowcount
        EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
        IF @err <> 0 GOTO Err_Handler







-- ***********************************   Future GL Account **************************************
--Remove from Account Summary And Account List
    DELETE  RInvAccountSummary
    FROM    RInvAccountSummary
    WHERE   LongAccount = ''Future GL''
    DELETE  RInvAccountList
    FROM    RInvAccountList
    WHERE   LongAccount = ''Future GL''

    SET @Check2 = ( SELECT  COUNT(*)
                    FROM    F0911
                    WHERE   GLANI = ''Future GL'' )
    IF @Check2 = 0 
        BEGIN
            EXEC Update_Server_Log @@Step,
                ''No future GL transactions found, skipping processing''
        END

    IF @Check2 > 0 
        BEGIN


            DECLARE C2 CURSOR
                FOR SELECT  CompanyNumber
                    FROM    RCompanies

            OPEN C2
            FETCH NEXT FROM C2 INTO @Company
            WHILE 		@@FETCH_STATUS = 0
                BEGIN


                    SET @Check2 = ( SELECT  COUNT(*)
                                    FROM    F0911
                                    WHERE   GLANI = ''Future GL'' AND
                                            GLCO = @Company )

                    SET @@Process = ''Checking for future GL records for company '' + @Company
                    EXEC Update_Server_Log @@Step, @@Process
                    EXEC sp_Update_Trans_Results @@Step, @@Process, @Check2, 0


                    IF @Check2 > 0 
                        BEGIN


--Insert Future GL Account into Account List
                            SET @@Process = ''Adding future to account list for company '' + @Company
                            EXEC Update_Server_Log @@Step, @@Process

                            INSERT  INTO RInvAccountList
                            VALUES  (
                                      @Company,
                                      ''ZZZZZZZZ'',
                                      '''',
                                      '''',
                                      '''',
                                      ''Future GL'',
                                      '''',
                                      0,
                                      0,
                                      0,
                                      0,
                                      0,
                                      0,
                                      0,
                                      0,
                                      0,
                                      0,
                                      0,
                                      0,
                                      0,
                                      0,
                                      0,
                                      0 )


		--Transaction logging		
                            SELECT  @err = @@error,
                                    @rowc = @@rowcount
                            EXEC sp_Update_Trans_Results @@Step, @@Process,
                                @rowc, @err
                            IF @err <> 0 
                                GOTO Err_Handler


--Insert Future GL Account in Account Summary Table
                            SET @@Process = ''Adding future account to account summary for company '' + @Company
                            EXEC Update_Server_Log @@Step, @@Process

                            INSERT  INTO RInvAccountSummary
                                    SELECT  A.CompanyNumber,
                                            A.LongAccount,
                                            0,
                                            B.MaxPeriodEnds,
                                            0,
                                            0,
                                            0,
                                            ''End'',
                                            0,
                                            0,
                                            0,
                                            0,
                                            0,
                                            0,
                                            0,
                                            0,
                                            0,
                                            0,
                                            0,
                                            ''End'',
                                            0,0
                                    FROM    RInvAccountList A 
                                    INNER JOIN RCompanies B
                                            ON ( A.CompanyNumber = B.CompanyNumber )
                                    WHERE   LongAccount = ''Future GL'' AND
                                            A.CompanyNumber = @Company

		--Transaction logging		
                            SELECT  @err = @@error,
                                    @rowc = @@rowcount
                            EXEC sp_Update_Trans_Results @@Step, @@Process,
                                @rowc, @err
                            IF @err <> 0 
                                GOTO Err_Handler


                        END

                    FETCH NEXT FROM C2 INTO @Company
                END

            CLOSE C2
            DEALLOCATE C2


--Update Future  GL period activity
            SET @@Process = ''Calculating future period activity'' 
            EXEC Update_Server_Log @@Step, @@Process


            UPDATE  RInvAccountSummary
            SET     PeriodGL = W.Amount
            FROM    RInvAccountSummary A,
                    ( SELECT    CompanyNumber,
                                InventoryAccount,
                                SUM(LedgerAmount) AS Amount
                      FROM      RCardexLedgerCompare
                      WHERE     InventoryAccount = ''Future GL''
                      GROUP BY  CompanyNumber,
                                InventoryAccount ) AS W
            WHERE   A.CompanyNumber = W.CompanyNumber AND
                    A.LongAccount = W.InventoryAccount

		--Transaction logging		
            SELECT  @err = @@error,
                    @rowc = @@rowcount
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
            IF @err <> 0 
                GOTO Err_Handler



--Update Future  GL period cardex activity
            SET @@Process = ''Calculating future period activity'' 
            EXEC Update_Server_Log @@Step, @@Process


            UPDATE  RInvAccountSummary
            SET     PeriodCardex = W.Amount
            FROM    RInvAccountSummary A,
                    ( SELECT    CompanyNumber,
                                InventoryAccount,
                                SUM(CardexAmount) AS Amount
                      FROM      RCardexLedgerCompare
                      WHERE     InventoryAccount = ''Future GL''
                      GROUP BY  CompanyNumber,
                                InventoryAccount ) AS W
            WHERE   A.CompanyNumber = W.CompanyNumber AND
                    A.LongAccount = W.InventoryAccount

		--Transaction logging		
            SELECT  @err = @@error,
                    @rowc = @@rowcount
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
            IF @err <> 0 
                GOTO Err_Handler



--Calculate the Ending Balance
            SET @@Process = ''Calculating future GL ending balance''
            EXEC Update_Server_Log @@Step, @@Process

            UPDATE  RInvAccountSummary
            SET     EndingGLBalance = BeginningBalance + PeriodGL
            FROM    RInvAccountSummary
            WHERE   LongAccount = ''Future GL''

		--Transaction logging		
            SELECT  @err = @@error,
                    @rowc = @@rowcount
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
            IF @err <> 0 
                GOTO Err_Handler




--Calculate Account Variance
            SET @@Process = ''Calculating beginning variance'' 
            EXEC Update_Server_Log @@Step, @@Process


            UPDATE  RInvAccountSummary
            SET     TransactionVariance = W.Amount
            FROM    RInvAccountSummary A,
                    ( SELECT    CompanyNumber,
                                InventoryAccount,
                                SUM(LedgerAmount) AS Amount
                      FROM      RCardexLedgerCompare
                      WHERE     InventoryAccount = ''Future GL'' AND
                                Status <> ''Manual Entry''
                      GROUP BY  CompanyNumber,
                                InventoryAccount ) AS W
            WHERE   A.CompanyNumber = W.CompanyNumber AND
                    A.LongAccount = W.InventoryAccount

		--Transaction logging		
            SELECT  @err = @@error,
                    @rowc = @@rowcount
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
            IF @err <> 0 
                GOTO Err_Handler


--Update Future  GL manual entries
            SET @@Process = ''Calculating future manual entries'' 
            EXEC Update_Server_Log @@Step, @@Process


            UPDATE  RInvAccountSummary
            SET     JournalEntries = W.Amount
            FROM    RInvAccountSummary A,
                    ( SELECT    CompanyNumber,
                                InventoryAccount,
                                SUM(LedgerAmount) AS Amount
                      FROM      RCardexLedgerCompare
                      WHERE     InventoryAccount = ''Future GL'' AND
                                Status = ''Manual Entry''
                      GROUP BY  CompanyNumber,
                                InventoryAccount ) AS W
            WHERE   A.CompanyNumber = W.CompanyNumber AND
                    A.LongAccount = W.InventoryAccount

		--Transaction logging		
            SELECT  @err = @@error,
                    @rowc = @@rowcount
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
            IF @err <> 0 
                GOTO Err_Handler


--Calculate Total Out of Balance
            SET @@Process = ''Calculating future gl out of balance''
            EXEC Update_Server_Log @@Step, @@Process

            UPDATE  RInvAccountSummary
            SET     OutofBalance = ( TransactionVariance + JournalEntries )
            FROM    RInvAccountSummary
            WHERE   LongAccount = ''Future GL''

		--Transaction logging		
            SELECT  @err = @@error,
                    @rowc = @@rowcount
            EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
            IF @err <> 0 
                GOTO Err_Handler

        END		--End Of Future GL processing


    SET @@Process = ''Clearing discrepant AAIs''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE  RAAIDiscr
    FROM    RAAIDiscr A 
    INNER JOIN v_Unused_Accounts B
            ON A.CurrentAccount = B.LongAccount

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler



    SET @@Process = ''Clearing unused accounts from account list''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE  RInvAccountList
    FROM    RInvAccountList A 
    INNER JOIN v_Unused_Accounts B
            ON A.LongAccount = B.LongAccount


		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler




    SET @@Process = ''Clearing unused accounts from summary''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE  RInvAccountSummary
    FROM    RInvAccountSummary A 
    INNER JOIN v_Unused_Accounts B
            ON A.LongAccount = B.LongAccount

		--Transaction logging		
    SELECT  @err = @@error,
            @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 
        GOTO Err_Handler





-- Validate data
    SET @@Process = ''Validating Data''
    EXEC Update_Server_Log @@Step, @@Process



TRUNCATE TABLE dbo.RValidation
--Summarize F41021
    SET @@Process = ''Summing F41021 ...''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RValidation
            SELECT  ''F41021'', ''Raw Data'', Case When SUM(LIPQOH) * -1 IS NULL Then 0 Else SUM(LIPQOH) * -1 End, 0, 0, 0
            FROM    dbo.F41021 


--Summarize F4111
    SET @@Process = ''Summing F4111 ...''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RValidation
            SELECT  ''F4111'', ''Raw Data'', 0, 0, Case When SUM(ilpaid) * -1 Is Null Then 0 Else SUM(ilpaid) * -1 End , 0
            FROM    dbo.F4111B CX 
            INNER JOIN RCompanies Comp  ON ( CX.ILKCO = Comp.CompanyNumber ) 
            INNER JOIN RFiscalCalendar CAL ON ( CX.ILKCO = CAL.CompanyNumber AND CX.PeriodEnds = CAL.PeriodEnds )


--Summarize F0911
    SET @@Process = ''Summing F0911 ...''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RValidation
            SELECT  ''F0911'', ''Raw Data'', 0, 0, 0, Case When SUM(glaa) * -1 Is Null Then 0 Else SUM(glaa) * -1 End
            FROM    dbo.F0911 GL 
            INNER JOIN RCompanies Comp  ON ( GL.GLCO = Comp.CompanyNumber )


-- Start RPerpetualInv
    SET @@Process = ''Summing Perpetual ...''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RValidation
            SELECT  ''RPerpetualInv'', ''Invalid Account'',
                    CASE WHEN SUM(dbo.RPerpetualInv.QuantityOnHand) IS NULL THEN 0 ELSE SUM(dbo.RPerpetualInv.QuantityOnHand) END, 0, 0, 0
            FROM    dbo.RPerpetualInv 
            INNER JOIN RCompanies Comp ON ( dbo.RPerpetualInv.CompanyNumber = Comp.CompanyNumber ) 
            LEFT OUTER JOIN dbo.RInvAccountList AL  ON ( dbo.RPerpetualInv.LongAccount = AL.LongAccount )
            WHERE   AL.LongAccount IS NULL AND dbo.RPerpetualInv.LongAccount NOT LIKE ''GL C%''

    INSERT  INTO RValidation
            SELECT  ''RPerpetualInv'', ''BaselineVar'',  0, CASE WHEN SUM(BalCXVar) IS NULL THEN 0 ELSE SUM(BalCXVar) * -1 END, 0, 0
            FROM    dbo.RInvAccountSummary A
            INNER JOIN RCompanies Comp ON ( A.CompanyNumber = Comp.CompanyNumber ) 
			WHERE   LongAccount Not In (''GL Class Not in Base Table'', ''Outside Operations'')


    INSERT  INTO RValidation
            SELECT  ''RPerpetualInv'', ''Invalid GLClass'',
                    CASE WHEN SUM(dbo.RPerpetualInv.QuantityOnHand) IS NULL THEN 0
                         ELSE SUM(dbo.RPerpetualInv.QuantityOnHand) END,
                    CASE WHEN SUM(dbo.RPerpetualInv.AmountOnHand) IS NULL THEN 0
                         ELSE SUM(dbo.RPerpetualInv.AmountOnHand) * -1 END, 0, 0
            FROM    dbo.RPerpetualInv 
			INNER JOIN RCompanies Comp ON ( dbo.RPerpetualInv.CompanyNumber = Comp.CompanyNumber )
            WHERE   dbo.RPerpetualInv.LongAccount = ''GL Class Not in Base Table''


    INSERT  INTO RValidation
            SELECT  ''RPerpetualInv'', ''Outside Ops'',
                    CASE WHEN SUM(dbo.RPerpetualInv.QuantityOnHand) IS NULL THEN 0
                         ELSE SUM(dbo.RPerpetualInv.QuantityOnHand)
                    END,
                    CASE WHEN SUM(dbo.RPerpetualInv.AmountOnHand) IS NULL THEN 0
                         ELSE SUM(dbo.RPerpetualInv.AmountOnHand) * -1 END, 0, 0
            FROM    dbo.RPerpetualInv 
            INNER JOIN RCompanies Comp ON ( dbo.RPerpetualInv.CompanyNumber = Comp.CompanyNumber )
            WHERE   dbo.RPerpetualInv.LongAccount = ''Outside Operations''


    INSERT  INTO RValidation
            SELECT  ''RPerpetualInv'', ''Valid Account'',
                    CASE WHEN SUM(dbo.RPerpetualInv.QuantityOnHand) IS NULL THEN 0
                         ELSE SUM(dbo.RPerpetualInv.QuantityOnHand) END,
                    CASE WHEN SUM(dbo.RPerpetualInv.AmountOnHand) IS NULL THEN 0
                         ELSE SUM(dbo.RPerpetualInv.AmountOnHand) * -1 END, 0, 0
            FROM    dbo.RPerpetualInv 
            INNER JOIN RCompanies Comp ON ( dbo.RPerpetualInv.CompanyNumber = Comp.CompanyNumber ) 
            INNER JOIN dbo.RInvAccountList AL ON ( dbo.RPerpetualInv.LongAccount = AL.LongAccount )
            WHERE   dbo.RPerpetualInv.LongAccount NOT IN (''GL Class Not in Base Table'', ''Outside Operations'' )



    SET @@Process = ''Summing Account Summary ...''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RValidation
            SELECT  ''RAccountSummary'', ''Summary'', 0, 0,
                    CASE WHEN SUM(dbo.RInvAccountSummary.PeriodCardex) + SUM(dbo.RInvAccountSummary.PeriodUnpostedCardex) IS NULL THEN 0
                         ELSE SUM(dbo.RInvAccountSummary.PeriodCardex) + SUM(dbo.RInvAccountSummary.PeriodUnpostedCardex) END,
                    CASE WHEN SUM(dbo.RInvAccountSummary.PeriodGL) IS NULL THEN 0
                         ELSE SUM(dbo.RInvAccountSummary.PeriodGL) END
            FROM    dbo.RInvAccountSummary 
            INNER JOIN RCompanies Comp  ON ( dbo.RInvAccountSummary.CompanyNumber = Comp.CompanyNumber )
            WHERE   GLRollOK <> ''BaseLine'' 


    UPDATE  RValidation
    SET     OnHandAmount = Case When W.Amount Is Null Then 0 Else W.Amount End
    FROM    RValidation,
            ( SELECT    SUM(AmountonHand) AS Amount
              FROM      dbo.RInvAccountSummary
			  INNER JOIN RCompanies Comp  ON ( dbo.RInvAccountSummary.CompanyNumber = Comp.CompanyNumber )
              WHERE     GLRollOK LIKE ''End%'' ) AS W
    WHERE   Tablenumber = ''RAccountSummary''

    SET @@Process = ''Calculating Totals ...''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO RValidation
            SELECT  ''Totals'', ''Variance'',  SUM(OnHandQty), SUM(OnHandAmount), SUM(CardexAmount),  SUM(GLAmount)
            FROM    RValidation

    SET @@Process = ''Validation Table Complete''
    EXEC Update_Server_Log @@Step, @@Process
    SELECT  @err = 0
    SET @rowc = ( SELECT COUNT(*) FROM RValidation )
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err


exec usp_Home_Page_Flow @Err OUTPUT



-- Update data capture results
    SET @DataValidation = ( SELECT  ABS(onhandqty) + ABS(onhandamount) + ABS(cardexamount) + ABS(glamount)
                            FROM    RValidation
                            WHERE   TableNumber = ''Totals'' )

    SET @@Process = ''Data error total : '' + CONVERT(VARCHAR(12), @DataValidation)
    EXEC Update_Server_Log @@Step, @@Process

    SELECT  @rowc = 1, @err = 0
    IF @DataValidation > 80000 BEGIN SET @err = 50002 END
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err


-- Successful Completion 
DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
SET		@@Process = ''Procedure completed sucessfully''
EXEC 	Update_Server_Log @@Step, @@Process 
    RETURN 0

-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 ) WITH Log
    RETURN -1
--End



' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_180_Account_Summary] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp_190_Variance_Tables]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_190_Variance_Tables]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'


CREATE PROCEDURE [dbo].[usp_190_Variance_Tables] ( @Err INT OUTPUT )
AS 
    DECLARE @@Step VARCHAR(30),
        @@Process VARCHAR(100),
        @rowc INT

    SET @@Step = ''190 Variance Tables''


--- Add Landed Cost GL Classes
    SET @@Process = ''Adding landed costs to ledger class table''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO dbo.RInvLedgerClasses
            SELECT DISTINCT
                    F.CompanyNumber, 
					F.GLClass,
                    F.BusinessUnit,
                    0,
                    0
            FROM    dbo.RAccountInstrExp F 
            LEFT OUTER JOIN dbo.RInvLedgerClasses R2 ON ( R2.CompanyNumber = F.CompanyNumber AND R2.GLClass = F.GLClass )
            WHERE   R2.CompanyNumber IS NULL AND F.TableNumber = ''4385''
            ORDER BY F.CompanyNumber, F.GLClass

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0  GOTO Err_Handler


--Update Variance by branch plant
    SET @@Process = ''Updating on hand variance in ledger class table by branch plant''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RInvLedgerClasses
    SET     OnHandVariance = G.AmountonHand
    FROM    dbo.RInvLedgerClasses T,
            ( SELECT    I.CompanyNumber,
                        I.GLCLass,
                        I.BranchPlant,
                        SUM(I.AmountonHand) AS AmountOnHand
              FROM      RPerpetualInv I
              WHERE     I.LongAccount = ''GL Class not in Base Table''
              GROUP BY  I.CompanyNumber,
                        I.GLCLass,
                        I.BranchPlant
              HAVING    SUM(I.AmountonHand) <> 0 ) AS G
    WHERE   T.CompanyNumber = G.CompanyNumber AND
            T.GLClass = G.GLClass AND
            G.BranchPlant = T.ProjectNumber

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0  GOTO Err_Handler


-- Update variance by GL Class
    SET @@Process = ''Updating on hand variance in ledger class table by gl class''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RInvLedgerClasses
    SET     OnHandVariance = G.AmountonHand
    FROM    dbo.RInvLedgerClasses T,
            ( SELECT    I.CompanyNumber,
                        I.GLCLass,
                        SUM(I.AmountonHand) AS AmountOnHand
              FROM      RPerpetualInv I
              WHERE     I.LongAccount = ''GL Class not in Base Table''
              GROUP BY  I.CompanyNumber,
                        I.GLCLass
              HAVING    SUM(I.AmountonHand) <> 0 ) AS G
    WHERE   T.CompanyNumber = G.CompanyNumber AND
            T.GLClass = G.GLClass AND
            T.OnHandVariance = 0

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0  GOTO Err_Handler


-- Calculate variance by project number
    SET @@Process = ''Calculating cardex variance by project number''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RInvLedgerClasses
    SET     CardexVariance = G.ILPAID
    FROM    dbo.RInvLedgerClasses T,
            ( SELECT    CX.ILKCO,
                        CX.ILGLPT,
                        CX.ILMCU,
                        SUM(CX.ILPAID) AS ILPAID
              FROM      F4111B CX
              WHERE     CX.InventoryAccount = ''GL Class not in Base Table''
              GROUP BY  CX.ILKCO,
                        CX.ILGLPT,
                        CX.ILMCU ) AS G
    WHERE   T.CompanyNumber = G.ILKCO AND
            T.GLClass = G.ILGLPT AND
            T.ProjectNumber = G.ILMCU

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0  GOTO Err_Handler


-- Calculate variance by GL class
    SET @@Process = ''Calculating cardex variance by GLClass''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RInvLedgerClasses
    SET     CardexVariance = G.ILPAID
    FROM    dbo.RInvLedgerClasses T,
            ( SELECT    CX.ILKCO,
                        CX.ILGLPT,
                        SUM(CX.ILPAID) AS ILPAID
              FROM      F4111B CX
              WHERE     CX.InventoryAccount = ''GL Class not in Base Table''
              GROUP BY  CX.ILKCO,
                        CX.ILGLPT ) AS G
    WHERE   T.CompanyNumber = G.ILKCO AND
            T.GLClass = G.ILGLPT AND
            T.CardexVariance = 0

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0  GOTO Err_Handler


--Insert Recommended Adds to AAI base table
    SET @@Process = ''Adding recommended adds to AAI base table''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO dbo.RAccountInstr
            SELECT DISTINCT
                    Const.AAITableNum,
                    LC.CompanyNumber,
                    '''',
                    Const.AAIDocType,
                    LC.GLClass,
                    '''',
                    '''',
                    '''',
                    ''GL Class Not in Base Table'',
                    ''5'',
                    ''Base AAI - Recommended Add''
            FROM    dbo.RInvLedgerClasses LC 
            LEFT OUTER JOIN dbo.RAccountInstr AI1
                    ON ( LC.CompanyNumber = AI1.CompanyNumber AND
                         LC.GLClass = AI1.GLClass ) 
            INNER JOIN dbo.RConstants CONST
                    ON ( 1 = 1 )
            WHERE   LC.OnHandVariance <> 0 AND
                    LC.GLClass <> ''''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0  GOTO Err_Handler


-- ******************* Unposted Tables *******************************

    TRUNCATE TABLE	dbo.RUnpostedBatches
    TRUNCATE TABLE	dbo.RUnpostedCardex

-- Unposted Batch Table
    SET @@Process = ''Creating unposted batch report''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO dbo.RUnpostedBatches
            SELECT DISTINCT 
					F.PeriodEnds,
                    F.GLUSER,
                    F.GLCO,
                    F.GLANI,
                    F.GLICU,
                    F.GLICUT,
                    SUM(F.GLAA) AS GLAA,
						Case 	When ICIAPP Is Null Then ''Missing Batch Header''
							When ICIAPP = ''P'' Then ''Pending Approval''
							Else ''Approved'' End As Approval_Status,
						Case 	When ICIST Is Null Then ''Missing Batch Header''
							When ICIST = '' '' Then ''Pending''
							When ICIST = ''A'' Then ''Approved''
							When ICIST = ''D'' Then ''Posted''
							When ICIST = ''E'' Then ''Error''
							When ICIST = ''P'' Then ''Posting''
							When ICIST = ''U'' Then ''In Use'' End As Posting_Status
            FROM    F0911 F 
            INNER JOIN dbo.RCompanies Comp ON ( Comp.CompanyNumber = F.GLCO )
			Left Outer Join	vcr_F0011 On (GLICU = ICICU And GLICUT = ICICUT)
            WHERE   GLPOST <> ''P''
            GROUP BY F.PeriodEnds,
                    F.GLUSER,
                    F.GLCO,
                    F.GLICU,
                    F.GLICUT,
                    F.GLANI,
					ICIAPP,
					ICIST
            ORDER BY F.PeriodEnds,
                    F.GLUSER

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0  GOTO Err_Handler


-- Unposted Cardex Table
    SET @@Process = ''Creating unposted cardex report''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO dbo.RUnpostedCardex
            SELECT	CompanyNumber, C.InventoryAccount, DocType, DocNumber, OrderType, ILCRDJ, C.PeriodEnds, SUM(ILPAID), '''', LTRIM(B.ILMCU)
            FROM    dbo.RCardexLedgerCompare C
            INNER JOIN F4111B B 
                    ON ( C.CompanyNumber = B.ILKCO AND
                         C.InventoryAccount = B.InventoryAccount AND
                         C.PeriodEnds = B.PeriodEnds AND
                         C.DocType = B.ILDCT AND
                         C.DocNumber = B.ILDOC AND
                         C.OrderType = B.ILDCTO )
            WHERE   Status IN ( ''Sales Update Required'', ''Mfg Accounting Required'' )
            GROUP BY CompanyNumber, C.InventoryAccount, DocType, DocNumber, OrderType, ILCRDJ, C.PeriodEnds, B.ILMCU

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0  GOTO Err_Handler



-- Update Work Order Status
    SET @@Process = ''Updating work order status''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RUnpostedCardex
    SET     Status = WASRST
    FROM    dbo.RUnpostedCardex 
    INNER JOIN vcr_F4801
            ON ( CompanyNumber = WACO AND
                 DocNumber = WADOCO )
    WHERE   DocType IN ( ''IC'', ''IM'', ''LC'', ''LM'' )

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0  GOTO Err_Handler


-- Update Sales Order Status
    SET @@Process = ''Updating sales order status''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  dbo.RUnpostedCardex
    SET     Status = SDNXTR
    FROM    dbo.RUnpostedCardex,
            ( SELECT    SDCO,
                        SDDCTO,
                        SDDOCO,
                        SDMCU,
                        MIN(SDNXTR) AS SDNXTR
              FROM      F42119
		 --Where SDDGL = 0
              GROUP BY  SDCO,
                        SDDCTO,
                        SDDOCO,
                        SDMCU ) AS T
    WHERE   CompanyNumber = SDCO AND
            DocType = T.SDDCTO AND
            DocNumber = SDDOCO AND
            BranchPlant = LTRIM(SDMCU)

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0  GOTO Err_Handler

-- Remove netted work orders
    SET @@Process = ''Removing netted work orders''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE  RUnpostedCardex
    FROM    RUnpostedCardex A 
    INNER JOIN v_Unposted_Cardex_Net_WO B
            ON ( A.CompanyNumber = B.CompanyNumber AND
                 A.LongAccount = B.LongAccount AND
                 A.PeriodEnds = B.PeriodEnds AND
                 A.DocNumber = B.DocNumber AND
                 A.OrderType = B.OrderType )

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0  GOTO Err_Handler


-- Remove netted sales orders
    SET @@Process = ''Removing netted sales orders''
    EXEC Update_Server_Log @@Step, @@Process


		Delete	RUnpostedCardex
		From	RUnpostedCardex A,
				(Select CompanyNumber, PeriodEnds, Sum(TransactionAmount) AS Amount
				From RUnpostedCardex
				Where Status = ''999''
				Group By CompanyNumber, PeriodEnds
				Having Sum(TransactionAmount) = 0) As W
		Where	A.CompanyNumber = W.CompanyNumber And A.PeriodEnds = W.PeriodEnds

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0  GOTO Err_Handler


-- Successful Completion 
DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
SET		@@Process = ''Procedure completed sucessfully''
EXEC 	Update_Server_Log @@Step, @@Process 
    RETURN 0

-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 ) WITH Log
    RETURN -1
--End















' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_190_Variance_Tables] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp_220_As_Of_Process]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_220_As_Of_Process]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE    PROCEDURE [dbo].[usp_220_As_Of_Process] ( @Err INT OUTPUT )
AS 
    DECLARE @@Step VARCHAR(30), @@Process VARCHAR(100), @rowc INT,  @intRowsToInsert Int, @Period SmallDateTime, @Company VARCHAR(5),
			@intRowCount Int, @IntLoops Int, @IntRowsToDelete Int, @dtLoop smalldatetime, @IntRowsToUpdate Int
    SET @@Step = ''220 As Of Processing''

Truncate Table RInvAsOf

-- Add new records from Baseline table 
    SET @@Process = ''Loading As Of table .....''
    EXEC Update_Server_Log @@Step, @@Process
    
    DECLARE C1 CURSOR FOR 
	SELECT  Distinct	PeriodEnds, CompanyNumber
	FROM				RInvAccountSummary  
	Order By			PeriodEnds, CompanyNumber

    OPEN C1
    FETCH NEXT FROM C1 INTO @Period, @Company
    WHILE 		@@FETCH_STATUS = 0
    BEGIN
    
    SET @@Process = ''Inserting Balance Forward; '' + Cast(@Period As Varchar(12)) + '' '' + @Company
    EXEC Update_Server_Log @@Step, @@Process

	INSERT  INTO RInvAsOf
            SELECT  C.PeriodEnds, A.CompanyNumber, A.LongAccount, A.BranchPlant, A.ShortItem, A.ItemNumber,
                    A.Location, A.Lot, PeriodBegins, 
					GLClass,
					0 As PeriodCardex, A.AmountonHand - A.AmountinCardex As AmountOnHand, 
					0 As PeriodQty, A.QuantityOnHand - A.QuantityinCardex As QuantityOnHand,
					UnitofMeasure, 
					'''', 
					'''', 
					'''', 
					'''', 
					'''',
					1,0,0
            FROM    RBaselinePerpetual A With (NOLOCK)
            INNER JOIN RInvAccountSummary C ON ( A.CompanyNumber = C.CompanyNumber AND A.LongAccount = C.LongAccount)
			Inner JOIN	RperpetualInv D On ( A.LongAccount = D.LongAccount And A.BranchPlant = D.BranchPlant And A.ItemNumber = D.ItemNumber And A.Location = D.Location And A.Lot = D.Lot)

			Where	C.PeriodEnds = @Period And A.CompanyNumber = @Company


		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0  GOTO Err_Handler
    
                FETCH NEXT FROM C1 INTO @Period, @Company 
    END

    CLOSE C1
    DEALLOCATE C1



DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS


-- Update the period cardex totals
    SET @@Process = ''Adding period cardex totals ...''
    EXEC Update_Server_Log @@Step, @@Process



    DECLARE C1 CURSOR FOR 
	SELECT  Distinct	PeriodEnds, CompanyNumber
	FROM				RInvAccountSummary  
	Order By			PeriodEnds, CompanyNumber

    OPEN C1
    FETCH NEXT FROM C1 INTO @Period, @Company
    WHILE 		@@FETCH_STATUS = 0
    BEGIN

    SET @@Process = ''Updating cardex totals; '' + Cast(@Period As Varchar(12)) + '' '' + @Company
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAsOf
    SET     PeriodCardex = D.Amount, PeriodQty = D.Quantity, UpdateFlag = 1
    FROM    RInvAsOf
    INNER JOIN v_Summarized_Cardex D
            ON ( RInvAsOf.PeriodEnds = D.PeriodEnds And
				 RInvAsOf.CompanyNumber = D.ILKCO AND RInvAsOf.LongAccount = D.InventoryAccount AND
                 RInvAsOf.BranchPlant = D.ILMCU AND RInvAsOf.ShortItem = D.ILITM AND
                 RInvAsOf.Location = D.ILLOCN AND RInvAsOf.Lot = D.ILLOTN)
	Where	RInvAsOf.PeriodEnds = @Period And RInvAsOf.CompanyNumber = @Company

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0  GOTO Err_Handler


            FETCH NEXT FROM C1 INTO @Period, @Company 
    END

    CLOSE C1
    DEALLOCATE C1




DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS


-- Roll forward on hand amounts/quantities from baseline to present
    SET @@Process = ''Rolling forward amounts and quantities ...''
    EXEC Update_Server_Log @@Step, @@Process

    DECLARE C1 CURSOR FOR 
	SELECT  Distinct	PeriodEnds, CompanyNumber
	FROM				RInvAccountSummary  
	Order By			PeriodEnds, CompanyNumber

    OPEN C1
    FETCH NEXT FROM C1 INTO @Period, @Company
    WHILE 		@@FETCH_STATUS = 0
    BEGIN

    SET @@Process = ''Rolling forward totals for; '' + Cast(@Period As Varchar(12)) + '' '' + @Company
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RInvAsOf
    SET     AmountOnHand = A.AmountonHand + T.Amount, QuantityonHand = A.QuantityonHand + T.Quantity
    FROM    RInvAsOf A,
            ( SELECT     X.PeriodEnds, X.CompanyNumber, X.LongAccount, X.BranchPlant, X.ShortItem,
                        X.Location, X.Lot, SUM(W.Amount) AS Amount, SUM(W.Quantity) AS Quantity
              FROM      RInvAsOf X,
                        ( SELECT    PeriodEnds, ILKCO, InventoryAccount, ILMCU, ILITM,
                                    ILLOCN,ILLOTN, SUM(ILPAID) AS Amount,SUM(ILTRQT) AS Quantity
                          FROM      F4111B
                          GROUP BY  ILKCO, InventoryAccount, PeriodEnds, ILMCU, ILITM, ILLOCN, ILLOTN ) AS W
              WHERE     X.CompanyNumber = W.ILKCO AND X.LongAccount = W.InventoryAccount AND
                        X.BranchPlant = W.ILMCU AND X.ShortItem = W.ILITM AND X.Location = W.ILLOCN AND
                        X.Lot = W.ILLOTN AND W.PeriodEnds <= X.PeriodEnds
              GROUP BY  X.PeriodEnds, X.CompanyNumber, X.LongAccount, X.BranchPlant, X.ShortItem, X.Location, X.Lot ) AS T
    WHERE   A.PeriodEnds = @Period And A.CompanyNumber = @Company And
			A.CompanyNumber = T.CompanyNumber AND A.LongAccount = T.LongAccount AND
            A.PeriodEnds = T.PeriodEnds AND  A.BranchPlant = T.BranchPlant AND
            A.ShortItem = T.ShortItem AND  A.Location = T.Location AND A.Lot = T.Lot

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0  GOTO Err_Handler


            FETCH NEXT FROM C1 INTO @Period, @Company
    END

    CLOSE C1
    DEALLOCATE C1



-- Successful Completion
DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
SET		@@Process = ''Procedure completed sucessfully''
EXEC 	Update_Server_Log @@Step, @@Process 
    RETURN 0

-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 ) WITH Log
    RETURN -1
--End








' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_220_As_Of_Process] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp_240_Update_Stats]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_240_Update_Stats]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

CREATE PROCEDURE [dbo].[usp_240_Update_Stats] ( @Err INT OUTPUT )
AS 
    DECLARE @@Step VARCHAR(30),
        @@Process VARCHAR(100),
        @rowc INT,
        @Cardex INT,
        @GL INT,
        @BalCXVar DECIMAL(30, 2),
        @Baseline INT,
        @Locations INT,
        @Accounts INT,
        @OOB DECIMAL(30, 2),
        @Warnings INT,
        @Errors INT,
        @DaysBack INT,
        @DataValidation FLOAT

--Make sure Counter columns exist in log files

    IF NOT EXISTS ( SELECT  *
                    FROM    INFORMATION_SCHEMA.COLUMNS
                    WHERE   TABLE_NAME = ''RServer_Log'' AND
                            COLUMN_NAME = ''Counter'' ) 
        BEGIN
            ALTER TABLE RServer_Log
            ADD Counter INT IDENTITY(1, 1)
        END

    IF NOT EXISTS ( SELECT  *
                    FROM    INFORMATION_SCHEMA.COLUMNS
                    WHERE   TABLE_NAME = ''RunHistory'' AND
                            COLUMN_NAME = ''Counter'' ) 
        BEGIN
            ALTER TABLE RunHistory
            ADD Counter INT IDENTITY(1, 1)
        END

		

    SET @Cardex = ( SELECT  COUNT(*)
                    FROM    F4111B )
    SET @GL = ( SELECT COUNT (*) FROM F0911 )
    SET @BalCXVar = ( SELECT    CASE WHEN SUM(BalCXVar) IS NULL THEN 0
                                     ELSE SUM(BalCXVar)
                                END AS Variance
                      FROM      RInvAccountSummary )
    SET @OOB = ( SELECT CASE WHEN SUM(OutofBalance) IS NULL THEN 0
                             ELSE SUM(OutofBalance)
                        END
                 FROM   RInvAccountSummary
                 WHERE  GLRollOK LIKE ''End%'' )
    SET @Baseline = ( SELECT    COUNT(*)
                      FROM      RBaseline )
    SET @Locations = ( SELECT   COUNT(*)
                       FROM     RBaselinePerpetual )
    SET @Accounts = ( SELECT    COUNT(*)
                      FROM      RInvAccountList )
    SET @Warnings = ( SELECT    COUNT(*)
                      FROM      v_Diagnostic2_Error
                      WHERE     ErrorNum BETWEEN 60000 And 69999 )
    SET @Errors = ( SELECT  COUNT(*)
                    FROM    v_Diagnostic2_Error
                    WHERE   ErrorNum BETWEEN 50000 And 59999 OR
                            ErrorNum BETWEEN 70000 And 99999 )
    SET @DaysBack = ( SELECT    CXDaysBack
                      FROM      RConstants )


    UPDATE  RunHistory
    SET     Baseline = @Baseline,
            Locations = @Locations,
            Cardex = @Cardex,
            GL = @GL,
            BalCXVar = @BalCXVar,
            Accounts = @Accounts,
            OOBalance = @OOB,
            Warnings = @Warnings,
            Errors = @Errors,
            DaysBack = @DaysBack
    FROM    RunHistory
    WHERE   Counter = ( SELECT  MAX(Counter)
                        FROM    RunHistory )

-- Successful Completion 
	EXEC Update_Server_Log ''RapidReconciler'', ''Successfully Completed''
    DBCC SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
    RETURN 0
	Update Statistics F4111B;
	Update Statistics F0911;
    RETURN 0

    err_handler:
    EXEC sp_Update_Trans_Results @@Step, @@Process, 0, @err

    RETURN 1


















' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_240_Update_Stats] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp_Fiscal_Calendar]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_Fiscal_Calendar]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Objects
-- usp_Fiscal_Calendar
-- usp_PeriodEndingDates

/****** Object:  StoredProcedure [dbo].[usp_Fiscal_Calendar]    Script Date: 04/02/2011 04:07:58 ******/
CREATE    PROCEDURE [dbo].[usp_Fiscal_Calendar] (@Err INT OUTPUT)
AS --****************************** 
-- RapidReconciler A101 Build Fiscal Calendar
--******************************

    DECLARE    @@Step VARCHAR(30), @@Process VARCHAR(100), @rowc INT
    SET @@Step = ''Fiscal Calendar''

    TRUNCATE TABLE	dbo.RFiscalCalendar
    TRUNCATE TABLE	dbo.RPeriodEnds


--Create Fiscal Calendar Table
    SET @@Process = ''Building Fiscal Calendar''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO dbo.RFiscalCalendar
    SELECT CCCO as CompanyNumber, CCNAME as CompanyName, CDFY as FiscalYear, Period, CDDFYJ as YearBegin, 

Case	When Period = 1 Then CDDFYJ
		When Period = 2 Then CDD01J+1
		When Period = 3 Then CDD02J+1
		When Period = 4 Then CDD03J+1
		When Period = 5 Then CDD04J+1
		When Period = 6 Then CDD05J+1
		When Period = 7 Then CDD06J+1
		When Period = 8 Then CDD07J+1
		When Period = 9 Then CDD08J+1
		When Period = 10 Then CDD09J+1
		When Period = 11 Then CDD10J+1
		When Period = 12 Then CDD11J+1
		When Period = 13 Then Case When CDD12J = CDD13J Then ''1/1/1900'' Else CDD12J + 1 END
		When Period = 14 Then Case When CDD13J = CDD14J Then ''1/1/1900'' Else CDD13J + 1 END
End AS PeriodBegin,

Case	When Period = 1 Then CDD01J
		When Period = 2 Then CDD02J
		When Period = 3 Then CDD03J
		When Period = 4 Then CDD04J
		When Period = 5 Then CDD05J
		When Period = 6 Then CDD06J
		When Period = 7 Then CDD07J
		When Period = 8 Then CDD08J
		When Period = 9 Then CDD09J
		When Period = 10 Then CDD10J
		When Period = 11 Then CDD11J
		When Period = 12 Then CDD12J
		When Period = 13 Then CDD13J
		When Period = 14 Then CDD14J
End AS PeriodEnd,
0,
0,
0,
31

	FROM dbo.T0010
	INNER JOIN RPeriods ON 1=1
	INNER JOIN vcr_F0008 ON CCDTPN = CDDTPN
	WHERE CCCO <> ''00000''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler


 
-- Removes Unused periods. Flexibility for 12,13 or 14 period accounting
    SET @@Process = ''Adjusting number of periods used''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE  RFiscalCalendar
    FROM    RFiscalCalendar
    WHERE   PeriodBeginsJ = 1

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler



--Remove Duplicate Periods
    SET @@Process = ''Removing duplicate periods''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE  RFiscalCalendar
    FROM    RFiscalCalendar
    WHERE   PeriodBeginsJ > PeriodEndsJ

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler



-- Build Period Ending Dates Table
    SET @@Process = ''Creating period ending dates table''
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO dbo.RPeriodEnds
            SELECT  CompanyNumber, D.CalendarJulian, PeriodEnds,
                    RIGHT(CAST(100 + DATEPART(MM, Dates) AS CHAR(3)), 2) + ''/'' + RIGHT(CAST(100 + DATEPART(DD, Dates) AS CHAR(3)), 2) + ''/'' + CAST(DATEPART(YYYY, Dates) AS CHAR(4)) + '' ''
            FROM    RFiscalCalendar 
            INNER JOIN Dates D  ON ( CalendarJulian >= PeriodBeginsJ AND CalendarJulian <= PeriodEndsJ )
            ORDER BY CompanyNumber, D.CalendarJulian

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler





--Remove periods prior to the minimum cutoff date
    SET @@Process = ''Clearing periods prior to cutoff date''
    EXEC Update_Server_Log @@Step, @@Process
 
    DELETE  RFiscalCalendar
    FROM    RFiscalCalendar FC
    WHERE   FC.PeriodEnds < (Select Min(PeriodCutoff) From RCompanies)

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler




-- Create MaxDate table
If Not Exists (Select * From sysobjects Where Name = N''MaxDate'')
Begin
Create Table dbo.MaxDate (CompanyNumber nVarchar(5), MaxPeriodEnds Datetime)
End


--Add max calendar date to companies table
    SET @@Process = ''Calculating maximum calendar date'' 
    EXEC Update_Server_Log @@Step, @@Process

    INSERT  INTO MaxDate
            SELECT  CompanyNumber, MAX(PeriodEnds) AS PeriodEnds
            FROM    RPeriodEnds
            Where	CDate <= GETDATE() + 1
            GROUP BY CompanyNumber

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0  GOTO Err_Handler


--**********
    SET		@@Process = ''Updating max period ends date by company''
    EXEC	Update_Server_Log @@Step, @@Process

    UPDATE  RCompanies
    SET     MaxPeriodEnds = T.MaxPeriodEnds
    FROM    RCompanies A 
    INNER JOIN MaxDate T ON ( T.CompanyNumber = A.CompanyNumber )

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler





--**********
    SET @@Process = ''Updating period ends for companies without cardex''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RCompanies
    SET     MaxPeriodEnds = T.MaxPeriodEnds
    FROM    RCompanies A,(Select Max(MaxPeriodEnds) As MaxPeriodEnds From MaxDate) As T
	Where	A.MaxPeriodEnds = 0


		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler





--Remove Non Inventory Companies
    SET @@Process = ''Removing non inventory companies''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE  RFiscalCalendar
    FROM    RFiscalCalendar A 
    WHERE   Not Exists (Select CompanyNumber From RCompanies B Where A.CompanyNumber = B.CompanyNumber)

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler



--Remove calendar periods beyond the maximum transaction date
    SET @@Process = ''Removing future periods''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE  RFiscalCalendar
    FROM    RFiscalCalendar A 
    WHERE   A.PeriodEnds > (Select Max(MaxPeriodEnds) From RCompanies)

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler





-- Calculate days in period
    SET @@Process = ''Calculating days in period''
    EXEC Update_Server_Log @@Step, @@Process

    UPDATE  RFiscalCalendar
    SET     DaysinPeriod = DATEDIFF(Day, PeriodBegins, PeriodEnds) + 1
    FROM    RFiscalCalendar A

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler





-- Adjust PeriodCutoff if the date set is not a beginning period date. Added 9/16/2005.
     DECLARE @Company VARCHAR(5)
    DECLARE C1 CURSOR
        FOR SELECT  CompanyNumber
            FROM    RCompanies

    OPEN C1
    FETCH NEXT FROM C1 INTO @Company
    WHILE 		@@FETCH_STATUS = 0
        BEGIN
            DECLARE @UserCutoff DATETIME
            DECLARE @MinPeriodBegins DATETIME
            DECLARE @MaxPeriodBegins DATETIME

            SET @UserCutoff = ( SELECT  PeriodCutoff
                                FROM    RCompanies
                                WHERE   CompanyNumber = @Company )
            SET @MinPeriodBegins = ( SELECT MIN(PeriodBegins)
                                     FROM   RFiscalCalendar
                                     WHERE  CompanyNumber = @Company )
            SET @MaxPeriodBegins = ( SELECT MAX(PeriodBegins)
                                     FROM   RFiscalCalendar
                                     WHERE  CompanyNumber = @Company )



            IF @UserCutoff < @MinPeriodBegins 
                BEGIN

                    SET @@Process = ''Adjusting user cutoff date up for company '' + @Company
                    EXEC Update_Server_Log @@Step, @@Process

                    UPDATE  RCompanies
                    SET     PeriodCutoff = T.PeriodBegins
                    FROM    RCompanies,
                            ( SELECT    CompanyNumber,
                                        MIN(PeriodBegins) AS PeriodBegins
                              FROM      RFiscalCalendar
                              WHERE     CompanyNumber = @Company
                              GROUP BY  CompanyNumber ) AS T
                    WHERE   RCompanies.CompanyNumber = T.CompanyNumber

						--Transaction logging		
					SELECT  @err = @@error, @rowc = @@rowcount
					EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
					IF @err <> 0 GOTO Err_Handler

                END




            IF @UserCutoff > @MinPeriodBegins 
                BEGIN

                    SET @@Process = ''Adjusting user cutoff date down for company '' + @Company
                    EXEC Update_Server_Log @@Step, @@Process

                    UPDATE  RCompanies
                    SET     PeriodCutoff = T.PeriodBegins
                    FROM    RCompanies,
                            ( SELECT    CompanyNumber,
                                        MIN(PeriodEnds) + 1 AS PeriodBegins
                              FROM      RFiscalCalendar
                              WHERE     CompanyNumber = @Company
                              GROUP BY  CompanyNumber ) AS T
                    WHERE   RCompanies.CompanyNumber = T.CompanyNumber

						--Transaction logging		
					SELECT  @err = @@error, @rowc = @@rowcount
					EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
					IF @err <> 0 GOTO Err_Handler

                END




            IF @UserCutoff > @MaxPeriodBegins 
                BEGIN

                    SET @@Process = ''Adjusting user cutoff date for company '' + @Company
                    EXEC Update_Server_Log @@Step, @@Process

                    UPDATE  RCompanies
                    SET     PeriodCutoff = T.PeriodBegins
                    FROM    RCompanies,
                            ( SELECT    CompanyNumber,
                                        MIN(PeriodBegins) AS PeriodBegins
                              FROM      RFiscalCalendar
                              WHERE     CompanyNumber = @Company
                              GROUP BY  CompanyNumber ) AS T
                    WHERE   RCompanies.CompanyNumber = T.CompanyNumber

						--Transaction logging		
					SELECT  @err = @@error, @rowc = @@rowcount
					EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
					IF @err <> 0 GOTO Err_Handler


                END


            DELETE  RFiscalCalendar
            FROM    RFiscalCalendar 
            INNER JOIN RCompanies C
                    ON ( RFiscalCalendar.CompanyNumber = C.CompanyNumber )
            WHERE   RFiscalCalendar.PeriodEnds < C.PeriodCutoff AND
                    RFiscalCalendar.CompanyNumber = @Company


            FETCH NEXT FROM C1 INTO @Company
        END

    CLOSE C1
    DEALLOCATE C1

If Exists(Select * From sysobjects Where Name = N''MaxDate'')
Begin
Drop Table MaxDate
End


-- Successful Completion
DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
SET		@@Process = ''Procedure completed sucessfully''
EXEC 	Update_Server_Log @@Step, @@Process  
    RETURN 0

-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 ) WITH Log
    RETURN -1


' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_Fiscal_Calendar] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp_Home_Page_Flow]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_Home_Page_Flow]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE    PROCEDURE [dbo].[usp_Home_Page_Flow] ( @Err INT OUTPUT )
AS 
    DECLARE @@Step VARCHAR(30), @@Process VARCHAR(100), @rowc INT
    SET @@Step = ''180A - Home Page Flow''


-- Create Table if it doesn''t exist

If Not Exists (Select * From sysobjects Where Name = N''RHome_Page_Flow'')
Begin

CREATE TABLE [dbo].[RHome_Page_Flow](
	[CompanyNumber] [nchar](10) NOT NULL,
	[Beginning_Var] [decimal](18, 2) NOT NULL CONSTRAINT [DF_RHome_Page_Flow_Beginning_Var]  DEFAULT ((0)),
	[GL_Variance] [decimal](18, 2) NOT NULL CONSTRAINT [DF_RHome_Page_Flow_GL_Variance]  DEFAULT ((0)),
	[Perp_Variance] [decimal](18, 2) NOT NULL CONSTRAINT [DF_RHome_Page_Flow_Perp_Variance]  DEFAULT ((0)),
	[Trans_Variance] [decimal](18, 2) NOT NULL CONSTRAINT [DF_RHome_Page_Flow_Trans_Variance]  DEFAULT ((0)),
	[Out_Of_Balance] [decimal](18, 2) NOT NULL CONSTRAINT [DF_RHome_Page_Flow_Out_Of_Balance]  DEFAULT ((0)),
	[PeriodEnds] [smalldatetime] NOT NULL CONSTRAINT [DF_RHome_Page_Flow_PeriodEnds]  DEFAULT ((0))
) ON [PRIMARY]


End

-- Clear Table
Truncate Table RHome_Page_Flow


-- Set Companies **********************************************
SET @@Process = ''Initializing Home Page Flow table ''
EXEC Update_Server_Log @@Step, @@Process

Insert Into RHome_Page_Flow
Select		CompanyNumber, 0, 0, 0, 0, 0, 0
From		v_Inventory_Companies

--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF		@err <> 0 GOTO Err_Handler



-- Update Beginning Out of Balance Amount By Company *****************************
SET @@Process = ''Updating beginning OOB''
EXEC Update_Server_Log @@Step, @@Process

Update	RHome_Page_Flow
Set		Beginning_Var = W.Variance
From	RHome_Page_Flow A,
		(Select CompanyNumber, Sum(AccountVariance) As Variance
		 From RInvAccountSummary
		 Where	GLRollOK = ''Baseline''
		 Group By CompanyNumber) As W
Where	 A.CompanyNumber = W.CompanyNumber

--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF		@err <> 0 GOTO Err_Handler







-- Update GL Integrity ******************************************
SET @@Process = ''Update GL Integrity''
EXEC Update_Server_Log @@Step, @@Process

Update	RHome_Page_Flow
Set		GL_Variance = W.Variance
From	RHome_Page_Flow A,
		(Select		A.CompanyNumber, Sum(B.BeginningBalance - A.EndingGLBalance) As Variance
		 FROM		RInvAccountSummary A 
		 INNER JOIN	RInvAccountSummary B ON ( A.CompanyNumber = B.CompanyNumber AND A.LongAccount = B.LongAccount )
		 WHERE		A.LongAccount NOT IN ( ''GL Class Not in Base Table'', ''Outside Operations'', ''Future GL'' )
					And A.GLRollOK = ''No'' AND DATEDIFF(Day, A.PeriodEnds, B.PeriodEnds) BETWEEN 1 And 50
		 Group By	A.CompanyNumber) As W
Where	 A.CompanyNumber = W.CompanyNumber

--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF		@err <> 0 GOTO Err_Handler



SET @@Process = ''Add unposted batches from current period''
EXEC Update_Server_Log @@Step, @@Process

Update	RHome_Page_Flow
Set		GL_Variance = GL_Variance + W.Variance
From	RHome_Page_Flow A,
		(Select		A.CompanyNumber, Sum(UnPostedBatchAmount) As Variance
		 FROM		RInvAccountSummary A 
		 WHERE		A.LongAccount NOT IN ( ''GL Class Not in Base Table'', ''Outside Operations'', ''Future GL'' )
					And A.GLRollOK Like ''End%''
		 Group By	A.CompanyNumber) As W
Where	 A.CompanyNumber = W.CompanyNumber


--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF		@err <> 0 GOTO Err_Handler




-- Update Perpetual Inventory Variance *****************************************
SET @@Process = ''Update Perpetual Integrity''
EXEC Update_Server_Log @@Step, @@Process

Update	RHome_Page_Flow
Set		Perp_Variance = W.Variance
From	RHome_Page_Flow A,
		(Select CompanyNumber, Sum(BaselineVar) As Variance
		 From RPerpetualInv
		 Where	LongAccount NOT IN ( ''GL Class not in Base Table'',''Outside Operations'', ''Future GL'' )
		 Group By CompanyNumber) As W
Where	 A.CompanyNumber = W.CompanyNumber

--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF		@err <> 0 GOTO Err_Handler





-- Update Transaction Variance **************************************************
SET @@Process = ''Updating Transaction variance ''
EXEC Update_Server_Log @@Step, @@Process

Update	RHome_Page_Flow
Set		Trans_Variance = W.Variance
From	RHome_Page_Flow A,
		(Select CompanyNumber, Sum(TransactionVariance) As Variance
		 From RInvAccountSummary
		 Where LongAccount NOT IN (''Outside Operations'', ''GL Class Not In Base Table'')
		 Group By CompanyNumber) As W
Where	 A.CompanyNumber = W.CompanyNumber


--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF		@err <> 0 GOTO Err_Handler




-- Calculate Out of Balance ******************************************
SET @@Process = ''Calculating OOB''
EXEC Update_Server_Log @@Step, @@Process

Update	RHome_Page_Flow
Set		Out_Of_Balance = (Beginning_Var + GL_Variance + Perp_Variance + Trans_Variance - W.Variance)
From	RHome_Page_Flow A,
		(Select CompanyNumber, Sum(PeriodUnpostedCardex) As Variance
		 From RInvAccountSummary
		 Where LongAccount NOT IN (''Outside Operations'', ''GL Class Not In Base Table'')
		 Group By CompanyNumber) As W
Where	 A.CompanyNumber = W.CompanyNumber

--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF		@err <> 0 GOTO Err_Handler



-- Calculate From Period ******************************************
SET @@Process = ''Calculating From Period''
EXEC Update_Server_Log @@Step, @@Process

Update	RHome_Page_Flow
Set		PeriodEnds = PeriodCutoff
From	RHome_Page_Flow A
Inner Join RCompanies B On (A.CompanyNumber = B.CompanyNumber)

--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF		@err <> 0 GOTO Err_Handler






-- Successful Completion 
DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
SET		@@Process = ''Procedure completed sucessfully''
EXEC 	Update_Server_Log @@Step, @@Process 
    RETURN 0


-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 ) WITH Log
    RETURN -1
--End' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_Home_Page_Flow] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp_PeriodEnding_Dates]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_PeriodEnding_Dates]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

CREATE PROCEDURE [dbo].[usp_PeriodEnding_Dates] ( @Err INT OUTPUT )
AS --******************************
-- RapidReconciler A108B Assign Period Ending Dates
--******************************



    DECLARE @@Step VARCHAR(30), @@Process VARCHAR(100), @rowc INT,@Period SmallDateTime, @Company VARCHAR(5), @branch varchar(12),
			@intRowCount Int, @IntLoops Int, @IntRowsToDelete Int, @IntRowsToUpdate Int, @Julian decimal(6,0)
    SET @@Step = ''Period Ending Dates''

    SET @@Process = ''Assigning Period Ending Dates ...''
    EXEC Update_Server_Log @@Step, @@Process

-- Assigning period ending dates to the 5 main transaction tables:
-- T4111B, T0911, T42119, T4211, T4311

-- If a cutoff date is changed by the user, records prior to that date will be deleted from 3 of the tables:
-- T4111B, T0911, T42119


-- Assign Period Ending Dates ********************************************************************************

-- T4111B
    SET @@Process = ''Checking T4111 ...''
    EXEC Update_Server_Log @@Step, @@Process

    DECLARE C1 CURSOR FOR 
	Select CompanyNumber From v_Inventory_Companies

    OPEN C1
    FETCH NEXT FROM C1 INTO @Company
    WHILE 		@@FETCH_STATUS = 0
    BEGIN


	SET @@Process = ''Assigning periods T4111B; '' + @Company
	EXEC Update_Server_Log @@Step, @@Process

--	UPDATE  T4111B
--	SET     PeriodEnds = 
--	Case	When ILDGL >  ''1901-01-01 00:00:00.000'' And ILKCOO <> ILKCO And ILDCTO In (Select Distinct OrigOrderType From v_RIntercoTypes) 	Then dbo.ufn_Get_Period_Ends (ILKCO, ILTRDJ, ''T4111'' )
--			When ILDGL >  ''1901-01-01 00:00:00.000'' Then dbo.ufn_Get_Period_Ends (ILKCO, ILDGL, ''T4111'' )
--			Else dbo.ufn_Get_Period_Ends (ILKCO, ILTRDJ, ''T4111'' ) End
--		FROM    T4111B A
--		WHERE   ILKCO = @Company

	SET @@Process = ''Based on GL Date; '' + @Company
	EXEC Update_Server_Log @@Step, @@Process

		UPDATE  T4111B
		SET     PeriodEnds = B.PeriodEnds
		FROM    T4111B A
		Inner Join RPeriodEnds B On ILKCO = B.CompanyNumber And B.CDate = ILDGL
		Where	ILKCO = @Company And ILDGL > ''1900-01-02 00:00:00.000''

			--Transaction logging		
		SELECT  @err = @@error, @rowc = @@rowcount
		EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
		IF		@err <> 0  GOTO Err_Handler


	SET @@Process = ''Based on Transaction Date; '' + @Company
	EXEC Update_Server_Log @@Step, @@Process

		UPDATE  T4111B
		SET     PeriodEnds = B.PeriodEnds
		FROM    T4111B A
		Inner Join RPeriodEnds B On ILKCO = B.CompanyNumber And B.CDate = ILTRDJ
		WHERE   ILKCO = @Company And ILDGL < ''1901-01-02 00:00:00.000''

			--Transaction logging		
		SELECT  @err = @@error, @rowc = @@rowcount
		EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
		IF		@err <> 0  GOTO Err_Handler

    FETCH NEXT FROM C1 INTO @Company 
    END

    CLOSE C1
    DEALLOCATE C1
    
    
-- ReClass Cardex period to current if in the future
	SET @@Process = ''Reclass future cardex transactions ''
	EXEC Update_Server_Log @@Step, @@Process
	
	Update	T4111B
	Set PeriodEnds = MaxPeriodEnds
	From	T4111B
	Inner Join RCompanies On (ILKCO = CompanyNumber)
	Where	PeriodEnds > GETDATE() + 32   
	
			--Transaction logging		
	SELECT  @err = @@error, @rowc = @@rowcount
	EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
	IF		@err <> 0  GOTO Err_Handler 


-- T0911
    SET @@Process = ''Checking T0911 ...''
    EXEC Update_Server_Log @@Step, @@Process

    DECLARE C1 CURSOR FOR 
	Select CompanyNumber From v_Inventory_Companies

    OPEN C1
    FETCH NEXT FROM C1 INTO @Company
    WHILE 		@@FETCH_STATUS = 0
    BEGIN

		SET @@Process = ''Assigning Periods T0911; '' + @Company
		EXEC Update_Server_Log @@Step, @@Process

--		UPDATE  dbo.T0911
--		SET     PeriodEnds = dbo.ufn_Get_Period_Ends (GLCO, GLDGJ, ''T0911'' )
--		FROM    dbo.T0911 GL
--		WHERE   GLCO = @Company

		UPDATE  dbo.T0911
		SET     PeriodEnds = B.PeriodEnds
		FROM    dbo.T0911 GL
		Inner Join RPeriodEnds B On GLCO = B.CompanyNumber And CDate = GLDGJ
		WHERE   GLCO = @Company

			--Transaction logging		
		SELECT  @err = @@error, @rowc = @@rowcount
		EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
		IF		@err <> 0  GOTO Err_Handler

    FETCH NEXT FROM C1 INTO @Company
    END

    CLOSE C1
    DEALLOCATE C1


-- T42119
    SET @@Process = ''Checking T42119 ...''
    EXEC Update_Server_Log @@Step, @@Process

    DECLARE C1 CURSOR FOR 
	Select CompanyNumber From RCompanies --v_Inventory_Companies

    OPEN C1
    FETCH NEXT FROM C1 INTO @Company
    WHILE 		@@FETCH_STATUS = 0
    BEGIN

		SET @@Process = ''Assigning Periods T42119; '' + @Company
		EXEC Update_Server_Log @@Step, @@Process

--		UPDATE  dbo.T42119
--		SET     PeriodEnds = dbo.ufn_Get_Period_Ends (SDCO, SDDGL, ''T42119'' )
--		FROM    dbo.T42119 SH
--		WHERE   SDCO = @Company

		UPDATE  dbo.T42119
		SET     PeriodEnds = B.PeriodEnds
		FROM    dbo.T42119 A
		Inner Join RPeriodEnds B On SDCO = B.CompanyNumber And CDate = SDDGL
		Where SDCO = @Company


		--Transaction logging		
		SELECT  @err = @@error, @rowc = @@rowcount
		EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
		IF		@err <> 0  GOTO Err_Handler

    FETCH NEXT FROM C1 INTO @Company
    END

    CLOSE C1
    DEALLOCATE C1




-- T4211
    SET @@Process = ''Checking T4211 ...''
    EXEC Update_Server_Log @@Step, @@Process

    DECLARE C1 CURSOR FOR 
	Select CompanyNumber From RCompanies --v_Inventory_Companies

    OPEN C1
    FETCH NEXT FROM C1 INTO @Company
    WHILE 		@@FETCH_STATUS = 0
    BEGIN


		SET @@Process = ''T4211; '' + @Company
		EXEC Update_Server_Log @@Step, @@Process

--		UPDATE  dbo.T4211
--		SET     PeriodEnds = dbo.ufn_Get_Period_Ends (SDCO, SDDGL, ''T4211'' )
--		FROM    dbo.T4211 A
--		WHERE   SDCO = @Company

		UPDATE  dbo.T4211
		SET     PeriodEnds = B.PeriodEnds
		FROM    dbo.T4211 A
		Inner Join RPeriodEnds B On SDCO = B.CompanyNumber And CDate = SDDGL
		Where SDCO = @Company

			--Transaction logging		
		SELECT  @err = @@error, @rowc = @@rowcount
		EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
		IF		@err <> 0  GOTO Err_Handler

    FETCH NEXT FROM C1 INTO @Company
    END

    CLOSE C1
    DEALLOCATE C1




--T4311

--    SET @@Process = ''Checking T4311 ...''
--    EXEC Update_Server_Log @@Step, @@Process
--
--    DECLARE C1 CURSOR FOR 
--	Select CompanyNumber From v_Inventory_Companies
--
--    OPEN C1
--    FETCH NEXT FROM C1 INTO @Company
--    WHILE 		@@FETCH_STATUS = 0
--    BEGIN
--
--		SET @@Process = ''T4311; '' + @Company
--		EXEC Update_Server_Log @@Step, @@Process
--
--		UPDATE  T4311
--		SET     PeriodEnds = dbo.ufn_Get_Period_Ends (PDCO, PDDGL, ''T4311'' )
--		FROM    T4311 A
--		WHERE   PDCO = @Company And A.PeriodEnds = 0
--
--			--Transaction logging		
--		SELECT  @err = @@error, @rowc = @@rowcount
--		EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
--		IF		@err <> 0  GOTO Err_Handler
--
--            FETCH NEXT FROM C1 INTO @Company
--    END
--
--    CLOSE C1
--    DEALLOCATE C1



-- Remove any records prior to cutoff date ***********************************************************************************
-- T Tables
-- T0911
    SET @@Process = ''Checking T0911 prior to cutoff ...''
    EXEC Update_Server_Log @@Step, @@Process

If Exists (Select *
			FROM		T0911 A 
			INNER JOIN	RCompanies COMP ON ( A.GLCO = COMP.CompanyNumber )
			WHERE		A.PeriodEnds < COMP.PeriodCutoff)

Begin

SELECT			@intRowCount = 1, @intLoops = 300
SELECT			@intRowsToDelete = Count(*)
    FROM		T0911 A 
    INNER JOIN	RCompanies COMP ON ( A.GLCO = COMP.CompanyNumber )
    WHERE		A.PeriodEnds < COMP.PeriodCutoff


WHILE			@intRowCount > 0 AND @intLoops > 0
BEGIN
	SET ROWCOUNT 100000

    SET @@Process = ''Remove GL prior to cutoff; '' + Convert(Varchar(12),@intRowsToDelete) + '' Left''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE		T0911
    FROM		T0911 A 
    INNER JOIN	RCompanies COMP ON ( A.GLCO = COMP.CompanyNumber )
    WHERE		A.PeriodEnds < COMP.PeriodCutoff

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0  GOTO Err_Handler

	SELECT		@intRowCount = @rowc
	SET ROWCOUNT 0
	SELECT		@intRowsToDelete = @intRowsToDelete - @intRowCount,	@intLoops = @intLoops - 1

END
End



-- T4111B
    SET @@Process = ''Checking T4111B prior to cutoff ...''
    EXEC Update_Server_Log @@Step, @@Process

If Exists (Select *
			FROM		T4111B A 
			INNER JOIN	RCompanies COMP ON ( A.ILKCO = COMP.CompanyNumber )
			WHERE		A.PeriodEnds > 0 And A.PeriodEnds < COMP.PeriodCutoff)

Begin

SELECT		@intRowCount = 1, @intLoops = 300
SELECT		@intRowsToDelete = Count(*)
FROM		T4111B A 
INNER JOIN	RCompanies COMP ON ( A.ILKCO = COMP.CompanyNumber )
WHERE		A.PeriodEnds > 0 And A.PeriodEnds < COMP.PeriodCutoff


WHILE	@intRowCount > 0 AND @intLoops > 0
BEGIN
	SET ROWCOUNT 100000

    SET @@Process = ''Remove cardex prior to cutoff; '' + Convert(Varchar(12),@intRowsToDelete) + '' Left''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE		T4111B
    FROM		T4111B A 
    INNER JOIN	RCompanies COMP ON ( A.ILKCO = COMP.CompanyNumber )
    WHERE		A.PeriodEnds > 0 And A.PeriodEnds < COMP.PeriodCutoff

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0  GOTO Err_Handler

	SELECT		@intRowCount = @rowc
	SET ROWCOUNT 0
	SELECT		@intRowsToDelete = @intRowsToDelete - @intRowCount,	@intLoops = @intLoops - 1

END
End



-- T42119
    SET @@Process = ''Checking T42119 prior to cutoff ...''
    EXEC Update_Server_Log @@Step, @@Process

If Exists (Select *
			FROM		T42119 A 
			INNER JOIN	RCompanies COMP ON ( A.SDCO = COMP.CompanyNumber )
			WHERE		A.PeriodEnds > 0 And A.PeriodEnds < COMP.PeriodCutoff)

Begin

SELECT			@intRowCount = 1, @intLoops = 300
SELECT			@intRowsToDelete = Count(*)
    FROM		T42119 A 
    INNER JOIN	RCompanies COMP ON ( A.SDCO = COMP.CompanyNumber )
    WHERE		A.PeriodEnds > 0 And A.PeriodEnds < COMP.PeriodCutoff


WHILE			@intRowCount > 0 AND @intLoops > 0
BEGIN
	SET ROWCOUNT 100000

    SET @@Process = ''Remove sales history prior to cutoff; '' + Convert(Varchar(12),@intRowsToDelete) + '' Left''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE		T42119
    FROM		T42119 A 
    INNER JOIN	RCompanies COMP ON ( A.SDCO = COMP.CompanyNumber )
    WHERE		A.PeriodEnds > 0 And A.PeriodEnds < COMP.PeriodCutoff

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0  GOTO Err_Handler

	SELECT		@intRowCount = @rowc
	SET ROWCOUNT 0
	SELECT		@intRowsToDelete = @intRowsToDelete - @intRowCount,	@intLoops = @intLoops - 1


END
End



-- F Tables
-- F0911
    SET @@Process = ''Checking F0911 prior to cutoff ...''
    EXEC Update_Server_Log @@Step, @@Process

If Exists (Select *
			FROM		F0911 A 
			INNER JOIN	RCompanies COMP ON ( A.GLCO = COMP.CompanyNumber )
			WHERE		A.PeriodEnds < COMP.PeriodCutoff)

Begin

SELECT			@intRowCount = 1, @intLoops = 300
SELECT			@intRowsToDelete = Count(*)
    FROM		F0911 A 
    INNER JOIN	RCompanies COMP ON ( A.GLCO = COMP.CompanyNumber )
    WHERE		A.PeriodEnds < COMP.PeriodCutoff


WHILE			@intRowCount > 0 AND @intLoops > 0
BEGIN
	SET ROWCOUNT 100000

    SET @@Process = ''Remove GL prior to cutoff; '' + Convert(Varchar(12),@intRowsToDelete) + '' Left''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE		F0911
    FROM		F0911 A 
    INNER JOIN	RCompanies COMP ON ( A.GLCO = COMP.CompanyNumber )
    WHERE		A.PeriodEnds < COMP.PeriodCutoff

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0  GOTO Err_Handler

	SELECT		@intRowCount = @rowc
	SET ROWCOUNT 0
	SELECT		@intRowsToDelete = @intRowsToDelete - @intRowCount,	@intLoops = @intLoops - 1

END
End


-- F4111B
    SET @@Process = ''Checking F4111 prior to cutoff ...''
    EXEC Update_Server_Log @@Step, @@Process

If Exists (Select *
			FROM		F4111B A 
			INNER JOIN	RCompanies COMP ON ( A.ILKCO = COMP.CompanyNumber )
			WHERE		A.PeriodEnds > 0 And A.PeriodEnds < COMP.PeriodCutoff)

Begin

SELECT			@intRowCount = 1, @intLoops = 300
SELECT			@intRowsToDelete = Count(*)
    FROM		F4111B A 
    INNER JOIN	RCompanies COMP ON ( A.ILKCO = COMP.CompanyNumber )
    WHERE		A.PeriodEnds > 0 And A.PeriodEnds < COMP.PeriodCutoff


WHILE			@intRowCount > 0 AND @intLoops > 0
BEGIN
	SET ROWCOUNT 100000

    SET @@Process = ''Remove cardex prior to cutoff; '' + Convert(Varchar(12),@intRowsToDelete) + '' Left''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE		F4111B
    FROM		F4111B A 
    INNER JOIN	RCompanies COMP ON ( A.ILKCO = COMP.CompanyNumber )
    WHERE		A.PeriodEnds > 0 And A.PeriodEnds < COMP.PeriodCutoff

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0  GOTO Err_Handler

	SELECT		@intRowCount = @rowc
	SET ROWCOUNT 0
	SELECT		@intRowsToDelete = @intRowsToDelete - @intRowCount,	@intLoops = @intLoops - 1

END
End

-- F42119
    SET @@Process = ''Checking F42119 prior to cutoff ...''
    EXEC Update_Server_Log @@Step, @@Process

If Exists (Select *
			FROM		F42119 A 
			INNER JOIN	RCompanies COMP ON ( A.SDCO = COMP.CompanyNumber )
			WHERE		A.PeriodEnds > 0 And A.PeriodEnds < COMP.PeriodCutoff)

Begin

SELECT			@intRowCount = 1, @intLoops = 300
SELECT			@intRowsToDelete = Count(*)
    FROM		F42119 A 
    INNER JOIN	RCompanies COMP ON ( A.SDCO = COMP.CompanyNumber )
    WHERE		A.PeriodEnds > 0 And A.PeriodEnds < COMP.PeriodCutoff


WHILE			@intRowCount > 0 AND @intLoops > 0
BEGIN
	SET ROWCOUNT 100000

    SET @@Process = ''Remove sales history prior to cutoff; '' + Convert(Varchar(12),@intRowsToDelete) + '' Left''
    EXEC Update_Server_Log @@Step, @@Process

    DELETE		F42119
    FROM		F42119 A 
    INNER JOIN	RCompanies COMP ON ( A.SDCO = COMP.CompanyNumber )
    WHERE		A.PeriodEnds > 0 And A.PeriodEnds < COMP.PeriodCutoff

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC	sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF		@err <> 0  GOTO Err_Handler

	SELECT		@intRowCount = @rowc
	SET ROWCOUNT 0
	SELECT		@intRowsToDelete = @intRowsToDelete - @intRowCount,	@intLoops = @intLoops - 1


END
End

-- Successful Completion 
	DBCC	SHRINKFILE (N''RapidReconciler_Log'') WITH NO_INFOMSGS
	SET		@@Process = ''Procedure completed sucessfully''
	EXEC 	Update_Server_Log @@Step, @@Process 
    RETURN 0


-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 ) WITH Log
    RETURN -1
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_PeriodEnding_Dates] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp_Remove_Netted_Transactions]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_Remove_Netted_Transactions]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[usp_Remove_Netted_Transactions] @@Step Varchar(30)  As

DECLARE @@Process VARCHAR(100), @rowc INT, @err Int

-- Removing Netted Transactions
Declare @Net Decimal(18,2)  Select  @Net = 0

Select @Net = Case When (Select ABS(Sum(CardexLedgerVariance))From RCardexLedgerCompare2 Where Status = ''Document Match'') Is Null Then 0
			  Else (Select ABS(Sum(CardexLedgerVariance))From RCardexLedgerCompare2 Where Status = ''Document Match'')End


If @Net <= (Select Threshold2 From RConstants)
Begin
    SET @@Process = ''Test Passed - '' + @@Step
    EXEC Update_Server_Log @@Step, @@Process

Delete RCardexLedgerCompare2
From RCardexLedgerCompare2
Where Status = ''Document Match''

		--Transaction logging		
    SELECT  @err = @@error, @rowc = @@rowcount
    EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
    IF @err <> 0 GOTO Err_Handler

End
Else
    SET @@Process = ''Test Failed - '' + @@Step
    EXEC Update_Server_Log @@Step, @@Process




-- Successful Completion 
    RETURN 0

-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 ) WITH Log
    RETURN -1' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp_Remove_Netted_Transactions] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2_Item_Roll_Forward]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2_Item_Roll_Forward]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[usp2_Item_Roll_Forward] (@BranchPlant varchar(12), @itemnumber varchar(25),
								@location varchar(20), @lot varchar(50)) As
Select	BranchPlant, 
		ItemNumber, 
		Location, 
		Lot,
		PeriodEnds,
		Sum(PeriodQty) As QtyChange,
		Sum(PeriodCardex) As AmountChange, 
		Sum(QuantityOnHand) As QOH, 
		Sum(AmountOnHand) As AOH
From  RInvAsOf 
Where BranchPlant = @BranchPlant And ItemNumber = @Itemnumber And Location = @Location And Lot = @Lot
Group By BranchPlant, ItemNumber, Location, Lot, PeriodEnds
Order By BranchPlant, ItemNumber, Location, Lot, PeriodEnds

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2_Item_Roll_Forward] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2DeleteRCompanies]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2DeleteRCompanies]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2DeleteRCompanies] ( @CompanyNumber CHAR(5) )
AS 

	set nocount on

    DECLARE @Notes VARCHAR(100)
    SET @Notes = ( SELECT   ''Deleted '' + @CompanyNumber )
    EXEC Update_Server_Log ''Company'', @Notes

    DELETE  UserCompany
    WHERE   CompanyNumber = @CompanyNumber

    DELETE  RCompanies
    WHERE   CompanyNumber = @CompanyNumber
	
	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2DeleteRCompanies] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2DeleteUsers]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2DeleteUsers]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2DeleteUsers] ( @UserID CHAR(10) )
AS 

	set nocount on

    DECLARE @Notes VARCHAR(100)

    SET @Notes = ( SELECT   ''Deleted User  '' + @UserID )
    EXEC Update_Server_Log ''Users'', @Notes

    DELETE  Users
    WHERE   UserID = @UserID

	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2DeleteUsers] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetAccountGLRollEnd]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetAccountGLRollEnd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[usp2GetAccountGLRollEnd](
	 @companyNumber varchar(5) = ''''
	,@accountnumber varchar(28) = ''''
	,@businessunit varchar(12) = ''''
	,@periodends smalldatetime = null
	,@excludeCompanies varchar(255) = null
	,@debug bit = 0
)
as


	set nocount on

	declare @sql nvarchar(4000)
	declare @where nvarchar(2000)
	
	set @sql = ''''
	set @where = ''''

	set @sql = @sql + ''

  SELECT  ias.CompanyNumber AS Company,
          ias.LongAccount AS Account,
          PeriodEnds AS [P/E],
          BeginningBalance AS [Beg Bal],
          PeriodGL AS [Per GL],
          EndingGLBalance AS [End GL Bal],
          GLRollOK AS [GL OK?],
          UnpostedBatchAmount AS [Unpst GL],
          AmountonHand AS [Perpetual],
          AccountVariance AS [Beg Var],
          PeriodUnpostedCardex AS [EndofDay],
          TransactionVariance AS [Variance],
          JournalEntries AS [JEs],
          OutofBalance AS [Out of Bal],
          BalCXVar AS [Item Roll],
          OOBRollOK AS [Var OK?],
          LTRIM(al.BusinessUnit) AS BusinessUnit,
          al.ObjectAccount
  FROM    RInvAccountSummary ias
  inner join rcompanies c on ias.companynumber = c.companynumber 
  INNER JOIN rinvaccountlist al
          ON ias.longaccount = al.longaccount AND
             ias.companynumber = al.companynumber
		where glrollok = ''''End''''''

	exec usp2GetStandardFilters
			@companynumber=@companyNumber
		, @companynumberalias = ''al''
		, @accountnumber = @accountNumber
		, @accountnumberalias = ''al''
		, @accountnumbercolname = ''longaccount''
		, @businessunit = @businessUnit
		, @businessunitalias = ''al''
		, @periodends = null
		, @periodendsalias = ''ias''
		, @excludecompanies = @excludeCompanies
		, @filterClause = @where output
	
	if ( len(@where) > 0 ) begin
		set @sql = @sql + ''
			AND '' + @where
	end

	if ( @debug = 1 ) print @sql
	exec sp_executeSQL @sql

	set nocount off' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetAccountGLRollEnd] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetAccounts]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetAccounts]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-----------------------------------------------------------------------------------------
CREATE Procedure [dbo].[usp2GetAccounts](
	 @companyNumber varchar(5) = ''''
	,@accountnumber varchar(28) = ''''
	,@businessunit varchar(12) = ''''
	,@excludeCompanies varchar(255) = null
	,@debug bit = 0
) AS
/*

	exec usp2GetAccounts 
		--@companyNumber=''01002''
		--,@businessunit = ''    10021000''
		--,@accountnumber=''10021000.1351  .002     ''
		@excludecompanies=''''
		,@debug=1

select * from v_report6_out_of_balance

*/
	set nocount on

	declare @sql nvarchar(4000)
	declare @where varchar(1024)

	-- select
	set @sql = ''
				select
							RInvAccountList.CompanyNumber as Company,
								RInvAccountList.BusinessUnit,
								RInvAccountList.LongAccount as Account,
								RInvAccountList.AccountDescription
							from RInvAccountList 
							Inner Join RCompanies  
							on (RInvAccountList.CompanyNumber = RCompanies.CompanyNumber)''

			
	-- where
	exec usp2GetStandardFilters
		@companynumber=@companyNumber
	, @companynumberalias = ''RInvAccountList''
	, @accountnumber = @accountnumber
	, @accountnumberalias = ''RInvAccountList''
	, @accountnumbercolname = ''longaccount''
	, @businessunit = @businessunit
	, @businessunitalias = ''RInvAccountList''
	, @periodends = null
	, @periodendsalias = ''''
	, @excludecompanies = @excludeCompanies
	, @filterClause = @where output
	
	if ( len(@where) > 0 ) begin
		set @sql = @sql + '' 
		WHERE '' + @where
	end
	
	-- don''t want dummy account rows
	if ( len(@where) = 0 ) begin
		set @sql = @sql + '' 
		WHERE ''
	end
	else begin
		set @sql = @sql + ''
			AND ''
	end

	set @sql = @sql + ''businessunit != ''''''''''

	-- order by
	set @sql = @sql + ''
		ORDER BY LongAccount''

	if ( @debug = 1 ) print ''['' + @sql + '']''
	exec sp_executeSQL @sql

	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetAccounts] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetAllCompanies]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetAllCompanies]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2GetAllCompanies]
AS 
	set nocount on

    SELECT  RCompanies.CompanyNumber,
            RCompanies.PeriodCutoff,
            RInvAccountList.ShortAccount,
            RInvAccountList.LongAccount,
            RInvAccountList.AccountDescription
    FROM    RCompanies 
    INNER JOIN RInvAccountList
            ON RCompanies.CompanyNumber = RInvAccountList.CompanyNumber
    ORDER BY RCompanies.CompanyNumber,
            RInvAccountList.LongAccount
	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetAllCompanies] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetAllCompaniesOnly]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetAllCompaniesOnly]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

create  PROCEDURE [dbo].[usp2GetAllCompaniesOnly] 


AS
/*
 exec [usp2GetAllCompaniesOnly]
*/
	set nocount on

	SELECT		CompanyNumber, 
			PeriodCutoff,
			SubLedgerWO,
			ExtCostDecimal As ''CurrencyDecimals''

	FROM         	RCompanies 
	Order By 	CompanyNumber

	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetAllCompaniesOnly] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetAllSystemVariables]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetAllSystemVariables]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2GetAllSystemVariables]
AS 
	set nocount on

    SELECT  * 
    FROM    RSystemVariables 
    where Name in (''ClientAcctNumber'',''ExpirationDate'',''LicenseKey'')
	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetAllSystemVariables] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetAllUser]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetAllUser]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2GetAllUser]
AS 
/*
exec usp2getalluser
*/
	set nocount on

    SELECT  Users.UserID, Users.Password, Users.usertypeid, ut.usertype, Users.active
    FROM    Users
			inner join usertypes ut on users.usertypeid = ut.usertypeid
	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetAllUser] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetBranchPlants]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetBranchPlants]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure [dbo].[usp2GetBranchPlants]
       @companyNumber varchar(5) = ''''
			,@accountnumber varchar(28) = ''''
			,@businessunit varchar(12) = ''''
			,@periodends smalldatetime = null
			,@excludeCompanies varchar(255) = null
			,@debug bit = 0
as
/*

exec usp2GetBranchPlants
	 @companynumber = ''01002''
	,@accountnumber = ''10021000.1351  .002     ''
	,@businessunit = ''''
	,@periodends = ''03/31/2007''
	,@excludeCompanies = ''''
	,@debug = 1

exec usp2GetBranchPlants
	 @companynumber = ''''
	,@accountnumber = ''10021000.1351  .002     ''
	,@businessunit = ''''
	,@periodends = ''03/31/2007''
	,@excludeCompanies = ''''
	,@debug = 1

exec usp2GetBranchPlants
	 @companynumber = ''''
	,@accountnumber = ''''
	,@businessunit = ''    11601000''
	,@periodends = ''03/31/2007''
	,@excludeCompanies = ''''
	,@debug = 1

*/
set nocount on

declare @where nvarchar(2000)
declare @sql nvarchar(4000)

set @where = ''''
set @sql = ''''

exec usp2GetStandardFilters
	@companynumber=@companyNumber
, @companynumberalias = ''rpi''
, @accountnumber = @accountNumber
, @accountnumberalias = ''rpi''
, @accountnumbercolname = ''LongAccount''
, @businessunit = @businessUnit
, @businessunitalias = ''ial''
, @periodends = @periodEnds
, @periodendsalias = ''rpi''
, @excludecompanies = @excludeCompanies
, @filterClause = @where output

if ( len(@where) > 0 ) begin
	set @where = '' 
	WHERE '' + @where
end

set @sql = ''select distinct branchplant 
from rperpetualinv rpi
	join RInvAccountList ial on rpi.longaccount = ial.longaccount''
	+ @where + ''
order by branchplant''

if ( @debug = 1 ) print @sql
exec sp_executeSQL @sql

--SELECT		distinct MCMCU as BranchPlant
--FROM			F0006
--WHERE			MCCO not in (select * from dbo.fn_SplitString(@excludeCompanies,'',''))
--ORDER BY 	MCMCU
	
set nocount off

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetBranchPlants] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetBusinessUnits]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetBusinessUnits]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  StoredProcedure [dbo].[usp2GetBusinessUnits]    Script Date: 10/29/2007 19:33:54 ******/
CREATE PROCEDURE [dbo].[usp2GetBusinessUnits]
 @companynumber varchar(5) = null
 ,@excludeCompanies varchar(255) = null
AS 
/*
	exec [usp2GetBusinessUnits] @excludecompanies = ''00124''

select distinct companynumber,businessunit from rinvaccountlist
*/
	set nocount on
	
	declare @excComps table (companynumber varchar(30) primary key)
	insert @excComps select * from dbo.fn_SplitString(@excludeCompanies,'','')

	if ( @companynumber is not null ) begin
		-- b/u''s for only this company
			SELECT DISTINCT
							BusinessUnit
			FROM    RInvAccountList
			WHERE   BusinessUnit IS NOT NULL AND
							LTRIM(RTRIM(BusinessUnit)) != '''' and
							companynumber = @companynumber
			ORDER BY BusinessUnit
	end
	else begin
		if ( @excludeCompanies is null ) begin
			SELECT DISTINCT
							CompanyNumber
							,BusinessUnit
			FROM    RInvAccountList
			WHERE   BusinessUnit IS NOT NULL AND
							CompanyNumber IS NOT NULL AND 
							LTRIM(RTRIM(BusinessUnit)) != ''''
			ORDER BY BusinessUnit
		end
		else begin
			SELECT DISTINCT
							CompanyNumber
							,BusinessUnit
			FROM    RInvAccountList
			WHERE   BusinessUnit IS NOT NULL AND
							CompanyNumber IS NOT NULL AND 
							LTRIM(RTRIM(BusinessUnit)) != ''''
							AND companynumber not in (select companynumber from @excComps)
			ORDER BY BusinessUnit
		end
	end

	set nocount off

/****** Object:  StoredProcedure [dbo].[usp2GetRInvAccountSummary]    Script Date: 10/31/2007 16:24:48 ******/
SET ANSI_NULLS ON
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetBusinessUnits] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetCompanies]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetCompanies]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'


/**********************************************************
Show period end for company
***********************************************************/
CREATE procedure [dbo].[usp2GetCompanies]
@excludeCompanies varchar(255) = null
as
/*
      exec usp2GetCompanies @excludecompanies=''foo,foo2,foor,''
*/
set nocount on

      if ( @excludeCompanies is not null ) begin
            SELECT            RCompanies.CompanyNumber, 
                                          convert(varchar(8),PeriodCutoff,1) as PeriodCutoff,
                                          ''From '' + isnull(CONVERT(VARCHAR(10), PeriodEnds, 101),'''') 
                                          + '' '' + FB91DWCR2.dbo.JDEGSCompanyMaster.CurrencyCode AS PeriodEnds
            FROM              RCompanies 
            left join dbo.RHome_Page_Flow
                  on RCompanies.CompanyNumber = dbo.RHome_Page_flow.CompanyNumber
            left join FB91DWCR2.dbo.JDEGSCompanyMaster
                on RCompanies.CompanyNumber = FB91DWCR2.dbo.JDEGSCompanyMaster.CompanyNumber      
            WHERE             RCompanies.companynumber not in (select * from dbo.fn_SplitString(@excludeCompanies,'',''))
            ORDER BY    RCompanies.CompanyNumber
      end 
      else begin
            SELECT            RCompanies.CompanyNumber, 
                                          convert(varchar(8),PeriodCutoff,1) as PeriodCutoff,
                                          ''From '' + isnull(CONVERT(VARCHAR(10), PeriodEnds, 101),'''') 
                                          + '' '' + FB91DWCR2.dbo.JDEGSCompanyMaster.CurrencyCode AS PeriodEnds
            FROM              RCompanies 
            left join dbo.RHome_Page_Flow
                  on RCompanies.CompanyNumber = dbo.RHome_Page_flow.CompanyNumber
            left join FB91DWCR2.dbo.JDEGSCompanyMaster
                on RCompanies.CompanyNumber = FB91DWCR2.dbo.JDEGSCompanyMaster.CompanyNumber      
            ORDER BY    RCompanies.CompanyNumber
      end


' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetCompanies] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetConstantsV3]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetConstantsV3]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE    PROCEDURE [dbo].[usp2GetConstantsV3]
AS
/*
exec dbo.usp2GetConstantsV3
*/
	set nocount on
 
    SELECT  AAITableNum,
            AAIDocType,
            UnitCostDecimal,
            --ExtCostDecimal,
            InventoryDecimal,
            Threshold1,
            Threshold2,
            XferSOType,
            XferPOType,
            DirSOType,
            DirPOType,
            OOPOType,
            CXDaysBack
    FROM    RConstants

	set nocount off' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetConstantsV3] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetHomePageData]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetHomePageData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'












CREATE procedure [dbo].[usp2GetHomePageData](
			 @companyNumber varchar(5) = ''''
			,@accountnumber varchar(28) = ''''
			,@businessunit varchar(12) = ''''
			,@periodends smalldatetime = null
			,@excludeCompanies varchar(255) = null
			,@debug bit = 0
) AS


set nocount on

declare @sql nvarchar(4000)
declare @where nvarchar(2000)

set @sql = ''''
set @where = ''''

exec usp2GetStandardFilters
	  @companynumber=@companyNumber
	, @companynumberalias = ''ias''
	, @accountnumber = @accountNumber
	, @accountnumberalias = ''ias''
	, @accountnumbercolname = ''longaccount''
	, @businessunit = @businessUnit
	, @businessunitalias = ''al''
	, @periodends = @periodends
	, @periodendsalias = ''ias''
	, @excludecompanies = @excludeCompanies
	, @filterClause = @where output
	
if ( @periodends is null ) begin
	
	
	set @sql = @sql + ''
		select
		BeginningOOB as BeginningOOB
		,GL
		,Perpetual
		,[End of Day]
		,[Transaction]
		, BeginningOOB + [PreGross OOB] as ''''Gross OOB''''
		, JE
		, BeginningOOB + [PreNet OOB] as ''''Net OOB''''
		from (
			Select      --CompanyNumber,
						--LongAccount,
						--PeriodEnds,
						
						isnull((select SUM(isnull(AccountVariance,0))
							From  RInvAccountSummary ias
								INNER JOIN RCompanies c On (ias.CompanyNumber = c.CompanyNumber)
								INNER JOIN rinvaccountlist al ON ias.longaccount = al.longaccount AND ias.companynumber = al.companynumber
								Where ias.LongAccount Not In ( ''''GL Class Not in Base Table'''',''''Outside Operations'''',''''Future GL'''' ) and GLRollOK=''''Baseline''''
						''
	if ( len(@where) > 0 ) begin set @sql = @sql + '' AND '' + @where	end
	set @sql = @sql + ''
						),0) As ''''BeginningOOB'''',
						
						isnull(sum(Case when GLRollOK = ''''Baseline'''' Then 0	
										when GLRollOK Like (''''End%'''') Then (EndingGLBalance - PeriodGL - BeginningBalance)
										Else UnpostedBatchAmount + (EndingGLBalance - PeriodGL - BeginningBalance)
						End),0) As ''''GL'''',
	

						isnull((select SUM(isnull(BalCXVar,0))
							From  RInvAccountSummary ias
								INNER JOIN RCompanies c On (ias.CompanyNumber = c.CompanyNumber)
								INNER JOIN rinvaccountlist al ON ias.longaccount = al.longaccount AND ias.companynumber = al.companynumber
								Where ias.LongAccount Not In ( ''''Outside Operations'''',''''Future GL'''' ) and GLRollOK=''''End''''
						''
	if ( len(@where) > 0 ) begin set @sql = @sql + '' AND '' + @where	end
	set @sql = @sql + ''
						),0) As ''''Perpetual'''',

	
	
						
--						isnull(sum(BalCXVar),0) As ''''Perpetual'''',
						
						
						isnull(sum(UnpostedCardexAmount),0) As ''''End of Day'''',
						isnull(sum(TransactionVariance),0) As ''''Transaction'''',
						
						isnull(sum(Case When GLRollOK = ''''Baseline'''' Then 0
										when GLRollOK Like (''''End%'''') Then (EndingGLBalance - PeriodGL - BeginningBalance) + BalCXVar + (UnpostedCardexAmount * -1) + TransactionVariance 
										Else UnpostedBatchAmount + (EndingGLBalance - PeriodGL - BeginningBalance) + BalCXVar + (UnpostedCardexAmount * -1) + TransactionVariance 
						End),0) As ''''PreGross OOB'''',
						
						isnull(sum(JournalEntries),0) As ''''JE'''',
						
						isnull(sum(Case When GLRollOK = ''''Baseline'''' Then 0 
										when GLRollOK Like (''''End%'''') Then (EndingGLBalance - PeriodGL - BeginningBalance) + BalCXVar + (UnpostedCardexAmount * -1) + TransactionVariance + JournalEntries
										Else UnpostedBatchAmount + (EndingGLBalance - PeriodGL - BeginningBalance) + BalCXVar + (UnpostedCardexAmount * -1) + TransactionVariance + JournalEntries
						End),0) As ''''PreNet OOB''''
			From  RInvAccountSummary ias
			INNER JOIN RCompanies c On (ias.CompanyNumber = c.CompanyNumber)
			INNER JOIN rinvaccountlist al ON ias.longaccount = al.longaccount AND ias.companynumber = al.companynumber
			Where ias.LongAccount Not In ( ''''GL Class Not in Base Table'''',''''Outside Operations'''',''''Future GL'''' )''
			
	if ( len(@where) > 0 ) begin set @sql = @sql + '' AND '' + @where	end		
	
	set @sql = @sql + '')a''
	
end else begin
							
	set @sql = @sql + ''
		Select      --CompanyNumber,
					--LongAccount,
					--PeriodEnds,
					isnull(sum(AccountVariance),0) As ''''BeginningOOB'''',
					isnull(sum(Case when GLRollOK = ''''Baseline'''' Then 0	when GLRollOK Like (''''End%'''') Then (EndingGLBalance - PeriodGL - BeginningBalance)
									Else UnpostedBatchAmount + (EndingGLBalance - PeriodGL - BeginningBalance)End),0) As ''''GL'''',
					isnull(sum(BalCXVar),0) As ''''Perpetual'''',
					isnull(sum(UnpostedCardexAmount),0) As ''''End of Day'''',
					isnull(sum(TransactionVariance),0) As ''''Transaction'''',
					isnull(sum(Case When GLRollOK = ''''Baseline'''' Then AccountVariance
									when GLRollOK Like (''''End%'''') Then AccountVariance + (EndingGLBalance - PeriodGL - BeginningBalance) + BalCXVar + (UnpostedCardexAmount * -1) + TransactionVariance 
						Else AccountVariance + UnpostedBatchAmount + (EndingGLBalance - PeriodGL - BeginningBalance) + BalCXVar + (UnpostedCardexAmount * -1) + TransactionVariance 
					End),0) As ''''Gross OOB'''',
					isnull(sum(JournalEntries),0) As ''''JE'''',
					isnull(sum(Case When GLRollOK = ''''Baseline'''' Then AccountVariance 
									when GLRollOK Like (''''End%'''') Then AccountVariance + (EndingGLBalance - PeriodGL - BeginningBalance) + BalCXVar + (UnpostedCardexAmount * -1) + TransactionVariance + JournalEntries
						Else AccountVariance + UnpostedBatchAmount + (EndingGLBalance - PeriodGL - BeginningBalance) + BalCXVar + (UnpostedCardexAmount * -1) + TransactionVariance + JournalEntries
					End),0) As ''''Net OOB''''
		From  RInvAccountSummary ias
		INNER JOIN RCompanies c On (ias.CompanyNumber = c.CompanyNumber)
		INNER JOIN rinvaccountlist al ON ias.longaccount = al.longaccount AND ias.companynumber = al.companynumber
		Where ias.LongAccount Not In ( ''''GL Class Not in Base Table'''',''''Outside Operations'''',''''Future GL'''' )
			''
			
	if ( len(@where) > 0 ) begin
		set @sql = @sql + ''
			AND '' + @where
	end
end
	
	
	if ( @debug = 1 ) print isnull(@sql,''null query'')
	exec sp_executeSQL @sql

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetHomePageData] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetItemRollIntegrityDialog]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetItemRollIntegrityDialog]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'






/********************* Procedures **********************************/

CREATE PROCEDURE [dbo].[usp2GetItemRollIntegrityDialog]
			 @companyNumber varchar(5) = ''''
			,@accountnumber varchar(28) = ''''
			,@businessunit varchar(12) = ''''
			,@excludeCompanies varchar(255) = null
			,@debug bit = 0
AS 

	set nocount on

	
declare @sql nvarchar(4000)
declare @where nvarchar(2000)

set @sql = ''''
set @where = ''''

exec usp2GetStandardFilters
	  @companynumber=@companyNumber
	, @companynumberalias = ''al''
	, @accountnumber = @accountNumber
	, @accountnumberalias = ''al''
	, @accountnumbercolname = ''longaccount''
	, @businessunit = '''' --@businessUnit
	, @businessunitalias = ''al''
	, @periodends = null
	, @periodendsalias = ''rpi''
	, @excludecompanies = @excludeCompanies
	, @filterClause = @where output
	

set @sql = @sql + ''
  SELECT	LTRIM(RTRIM(rpi.CompanyNumber)) AS Company,
  			Case When sum(estunits) <> 0 Then ''''RRQ'''' Else''''RRA'''' End As Reason,
  			rpi.LastRec as LastTrans,
			LTRIM(rpi.BranchPlant) AS Branch,
			rpi.ItemNumber,
			rpi.Location As Loc,
			rpi.Lot,
			Case When sum(estunits) = 0 Then 0 Else rpi.UnitCost End As UnitCost,
			Case When sum(estunits) <> 0 Then 0 Else Cast(sum(BaselineVar) * -1 As Decimal(18,2)) End AS AdjAmount,
			Sum(EstUnits) * -1 AS AdjQty,
			sum(EstUnits) AS QuantityVar,
			sum(BaselineVar) AS AmountVar,
			rpi.CostMethod As Meth,
			rpi.CostLevel As Lev
			--rpi.QuantityonHand AS QOH

  FROM		dbo.RPerpetualInv rpi
			inner join rcompanies c on rpi.companynumber = c.companynumber
			INNER JOIN  dbo.rinvaccountlist al ON (rpi.longaccount = al.longaccount AND al.companynumber = rpi.companynumber)
  WHERE 	(rpi.LongAccount != ''''Outside Operations'''' AND rpi.LongAccount != ''''Future GL'''') ''
  
if ( len(@where) > 0 ) begin
						set @sql = @sql + ''
						AND '' + @where
						end

set @sql = @sql + ''
	Group By    rpi.CompanyNumber, rpi.BranchPlant, rpi.ItemNumber, ItemDescription, rpi.Location, rpi.Lot, rpi.CostMethod, rpi.LastRec, rpi.GLClass, rpi.UnitCost, rpi.CostLevel
	Having Abs(sum(BaselineVar)) > (Select Threshold1 From RConstants) Or Abs(sum(EstUnits)) > 0
	
	
	Union
	
  SELECT	LTRIM(RTRIM(rpi.CompanyNumber)) AS Company,
  			''''RRV'''' As Reason,
  			Cast(AsOf As datetime) as LastTrans,
			Case When CostLevel = ''''1'''' Then '''''''' Else LTRIM(rpi.BranchPlant) End AS Branch,
			rpi.ItemNumber,
			Case When CostLevel In(''''1'''',''''2'''') Then '''''''' Else rpi.Location End As Loc,
			Case When CostLevel In(''''1'''',''''2'''') Then '''''''' Else rpi.Lot End As Lot,
			CalcAvg As UnitCost,
			Cast((CalcAvg - CurrCost) *QOH As Decimal(18,2)) AS AdjAmount,
			0 AS AdjQty,
			0 AS QuantityVar,
			0 AS AmountVar,
			''''02'''' As Meth,
			rpi.CostLevel As Lev
  FROM		dbo.RAvgCostUpdate rpi
inner join f4111b c on rpi.ukid = c.ilukid
INNER JOIN  dbo.rinvaccountlist al ON (c.inventoryaccount = al.longaccount AND al.companynumber = c.ilkco)
  WHERE 	Flag = ''''9'''' And Abs((CalcAvg - CurrCost) *QOH) > (Select Threshold1 From RConstants)''
  
if ( len(@where) > 0 ) begin
						set @sql = @sql + ''
						AND '' + @where
						end

set @sql = @sql + ''
	
	Order By    Company, Reason, Branch''
	
if ( @debug = 1 ) print isnull(@sql,''null query'')
exec sp_executeSQL @sql

  set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetItemRollIntegrityDialog] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetJournalEntries]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetJournalEntries]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE    Procedure [dbo].[usp2GetJournalEntries](
	 @companyNumber varchar(5) = ''''
	,@accountnumber varchar(28) = ''''
	,@businessunit varchar(12) = ''''
	,@periodends smalldatetime = null
	,@excludeCompanies varchar(255) = null
	,@debug bit = 0
) AS
/*

	exec usp2GetJournalEntries
	@companynumber=''01300''
	--,@accountnumber=''13051000.1351  .000     ''
	--@businessunit = ''102910002''
	--,@periodends=''03/31/2007''
	,@debug = 1


*/
	set nocount on

declare @sql nvarchar(4000)
declare @where varchar(1024)

-- select
set @sql = ''select je.* from v_Report7_Manual_JE je 
			inner join rcompanies c on je.company = c.companynumber
			left join dbo.rinvaccountlist ial on je.company = ial.companynumber and je.account = ial.longaccount''

	
-- where
exec usp2GetStandardFilters
	@companynumber=@companyNumber
, @companynumberalias = ''je''
,@companyNumberColName = ''company''
, @accountnumber = @accountNumber
, @accountnumberalias = ''je''
, @accountnumbercolname = ''account''
, @businessunit = @businessUnit
, @businessunitalias = ''ial''
, @periodends = @periodends
, @periodendsalias = ''je''
, @excludecompanies = @excludeCompanies
, @filterClause = @where output

if ( len(@where) > 0 ) begin
	set @sql = @sql + '' 
	WHERE '' + @where
end

-- order by
set @sql = @sql +  '' 
	    ORDER BY Company,
          PeriodEnds,
          DocType,
          DocNumber,
          Account''

if ( @debug = 1 ) print ''['' + @sql + '']''
exec sp_executeSQL @sql

set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetJournalEntries] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetKeyStringValues]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetKeyStringValues]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

CREATE procedure  [dbo].[usp2GetKeyStringValues]
(@Result varchar(1000) out )
as 
BEGIN
    select @Result = [dbo].[ufn_GetKeyStringValues]();
END

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetKeyStringValues] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetMissingUOMConversion]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetMissingUOMConversion]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2GetMissingUOMConversion] (
	@ItemNumber varchar(25) = null
)
AS
/*
	exec usp2GetMissingUOMConversion ''1607                     ''
*/
	set nocount on

	if ( @ItemNumber is null ) begin
		set @ItemNumber = ''%''
	end
	
	select * 
	from v_Integrity4_UOM_Conv
	where itemnumber like @ItemNumber

	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetMissingUOMConversion] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetMovementsReport]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetMovementsReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[usp2GetMovementsReport](
			 @branchPlant varchar(12) = ''''
			,@companyNumber varchar(5) = ''''
			,@accountnumber varchar(28) = ''''
			,@businessunit varchar(12) = ''''
			,@periodends smalldatetime
			,@excludeCompanies varchar(255) = null
			,@CommonUOM char(2) = null
			,@QuantityAmt char(1) = ''Q''
			,@debug bit = 0
) AS

/*
History
05/01/2008	raw	creation
05/06/2008	raw	do not require UOM
11/03/2008	raw	use ILKCO to filter F4111b by company (not ILKCOO)
11/05/2008	raw	get prior period end from RInvAccountSummary
11/26/2009	raw new parameter to sum quantity or amount
------------------------------------------------------------------

select f4111b.illitm,f4101.imdsc1,f4101.IMUOM1
from f4111b left join dbo.f4101 on f4101.imlitm = f4111b.illitm
group by illitm,imdsc1,imuom1

select top 100 * from f4101
select top 100 * from f4111b
select top 100 * from rperpetualinv

select distinct ildcto from dbo.f4111b

exec usp2GetMovementsReport
--	@branchplant = ''          BI''
	@companynumber = ''00100''
	,@accountnumber = ''''
	,@businessunit = ''''
	,@periodends = ''12/31/2009''
	,@excludeCompanies = ''''
	--,@commonUOM = ''KG''
	,@QuantityAmt = ''A''
	,@debug = 1


exec usp2GetMovementsReport
	--@branchplant = ''          BI''
	@companynumber = ''01002''
	,@accountnumber = ''10021000.1351  .002     ''
	,@businessunit = ''''
	,@periodends = ''03/31/2007''
	,@excludeCompanies = ''''
	,@commonUOM = ''''
	,@debug = 1


exec usp2GetMovementsReport
	@branchplant = ''          MA''
	,@companynumber = ''''
	,@accountnumber = ''10021000.1351  .002     ''
	,@businessunit = ''''
	,@periodends = ''03/31/2007''
	,@excludeCompanies = ''''
	,@commonUOM = ''EA''
	,@debug = 1

exec usp2GetMovementsReport
	@branchplant = ''          MA''
	,@companynumber = ''''
	,@accountnumber = ''''
	,@businessunit = ''    11601000''
	,@periodends = ''02/28/2007''
	,@excludeCompanies = ''''
	,@commonUOM = ''''
	,@debug = 1

exec usp2GetMovementsReport
	@branchplant = ''          SO''
	,@companynumber = ''01110''
	,@accountnumber = ''''
	,@businessunit = ''''
	,@periodends = ''03/31/2007''
	,@excludeCompanies = ''''
	,@commonUOM = ''''
	,@debug = 1

select * from rinvaccountlist

truncate table rmovementcolumn

insert rmovementcolumn(columntitle,columnfield,columncode1,columnsort) values(''Material to WO'',''ILDCT'',''IM'',1)
insert rmovementcolumn(columntitle,columnfield,columncode1,columnsort) values(''Work Order'',''ILDCT'',''IC'',2)
insert rmovementcolumn(columntitle,columnfield,columncode1,columnsort) values(''Phys Inv'',''ILDCT'',''PI'',3)
insert rmovementcolumn(columntitle,columnfield,columncode1,columnsort) values(''Adjust'',''ILDCT'',''IA'',4)
insert rmovementcolumn(columntitle,columnfield,columncode1,columnsort) values(''Re-Class'',''ILDCT'',''IR'',5)
insert rmovementcolumn(columntitle,columnfield,columncode1,columnsort) values(''Re-Grade'',''ILDCT'',''IK'',6)
insert rmovementcolumn(columntitle,columnfield,columncode1,columnsort) values(''Re-Pack'',''ILDCT'',''IP'',7)
insert rmovementcolumn(columntitle,columnfield,columncode1,columnsort) values(''Trans BP'',''ILDCTO'',''ST'',8)
insert rmovementcolumn(columntitle,columnfield,columncode1,columnsort) values(''Trans Int'',''ILDCT'',''IT'',9)
insert rmovementcolumn(columntitle,columnfield,columncode1,columnsort) values(''Purchase Orders'',''ILDCT'',''OV'',10)
insert rmovementcolumn(columntitle,columnfield,columncode1,columncode2,columnsort) values(''Shipments'',''ILDCTO'',''SO'',''SI'',11)
insert rmovementcolumn(columntitle,columnfield,columncode1,columncode2,columnsort) values(''Credit Returns'',''ILDCTO'',''CO'',''CI'',12)

select * from rmovementcolumn

*/

set nocount on 

declare @colTitle varchar(50)
declare @colField varchar(50)
declare @colCode1 varchar(2)
declare @colCode2 varchar(2)
declare @colCode3 varchar(2)
declare @colCode4 varchar(2)
declare @colCode5 varchar(2)
declare @colCode6 varchar(2)
declare @codes varchar(255)
declare @where varchar(2000)
declare @openWhere varchar(2000)
declare @closeWhere varchar(2000)
declare @uomWhere varchar(2000)
declare @sql varchar(8000)
declare @qry varchar(8000)
declare @qry2 varchar(8000)
declare @qryClose varchar(8000)
declare @selCols varchar(8000)
declare @varCalc varchar(4000)
declare @idx int
declare @lastPeriodEnd datetime
declare @error varchar(255)

-- sum columns
declare @movValueCol varchar(25)
declare @startEndValueCol varchar(25)

if ( @QuantityAmt = ''A'' ) begin
	set @movValueCol = ''ILPAID''
	set @startEndValueCol = ''AmountOnHand''
	set @CommonUOM = null
end else begin	
	set @movValueCol = ''ILTRQT''
	set @startEndValueCol = ''QuantityOnHand''
end

-- determine company number
if ( len(@companyNumber) = 0 ) begin
	if ( len(@businessUnit) > 0 ) begin
		-- use b/u to get company
		set @companynumber = (select top 1 CompanyNumber from dbo.RInvAccountList where BusinessUnit = @businessUnit)
	end else if ( len(@accountnumber) > 0 )  begin
		-- use acct number to get company
		set @companynumber = (select top 1 CompanyNumber from dbo.RInvAccountList where LongAccount = @accountnumber)
	end
end

if exists(select top 1 periodends
					from dbo.RInvAccountSummary
					where periodends < @PeriodEnds 
						and companynumber = @companyNumber ) begin

	set @lastPeriodEnd = (select top 1 periodends
												from dbo.RInvAccountSummary
												where periodends < @PeriodEnds 
													and companynumber = @companyNumber
												order by periodends desc)
end else begin
	-- no prior p/e, can''t get opening bal
	set @error = ''The period prior to the period ending '' + 
								CONVERT(VARCHAR(8), @PeriodEnds, 1) + 
								'' for company ['' + @companynumber + 
								''] could not be determined. Please check the RInvAccountSummary table.''
	RAISERROR (@error,11,1)
end

set @idx = 0
set @selCols = ''''
set @codes = ''''
set @where = ''''
set @openWhere = ''''
set @uomWhere = ''''
set @sql = ''''
set @qry = ''''
set @qry2 = ''''
set @qryClose = ''''
set @varcalc = '' isnull(openBal.Opening,0)''

if ( @CommonUOM = '''' ) set @CommonUOM = null

---------------------------------------------------------------------------------------
-- common where clause
exec usp2GetStandardFilters
	@companynumber=@companyNumber
, @companynumberalias = ''a''
, @companynumbercolname = ''ILKCO''
, @accountnumber = @accountNumber
, @accountnumberalias = ''a''
, @accountnumbercolname = ''InventoryAccount''
, @businessunit = @businessUnit
, @businessunitalias = ''ial''
, @periodends = @periodends
, @periodendsalias = ''a''
, @excludecompanies = @excludeCompanies
, @filterClause = @where output


if ( len(@where) > 0 ) begin
	set @where = '' AND '' + @where
end

if ( len(@branchplant) > 0 ) begin
	if ( len(@where) > 0 ) set @where = @where + '' AND ''
	set @where = @where + ''ILMCU = '''''' + @branchplant + ''''''''
end

---------------------------------------------------------------------------------------
-- common UOM
-- set up conversion factor table
set @sql = @sql + ''declare @conversions table (
	 ConverterBranchPlant varchar(12)
	,ConverterShortItem decimal(8,0)
	,ConverterUOM char(2)
	,ConverterCommonUOM char(2)
	,ConversionFactor decimal (18,6)

	Primary Key (ConverterBranchPlant,ConverterShortItem,ConverterUOM,ConverterCommonUOM)
)''

-- only fill UOM table if needed (STILL create table to allow left join below)
if ( @CommonUOM is not null ) begin
	-- insert needed conversion factors
	set @sql = @sql + ''
		insert @conversions(ConverterBranchPlant,ConverterShortItem,ConverterUOM,ConverterCommonUOM)
		select distinct BranchPlant,ShortItem,imuom1,'''''' + @CommonUOM + ''''''
			FROM    dbo.RInvAsOf a
				inner join dbo.RInvAccountList ial on a.LongAccount = ial.LongAccount 
				INNER JOIN dbo.F4101 ON ( ShortItem = IMITM )''

	-- uom filters, explicitly set p/e
	exec usp2GetStandardFilters
		@companynumber=@companyNumber
	, @companynumberalias = ''ial''
	, @accountnumber = @accountNumber
	, @accountnumberalias = ''a''
	, @accountnumbercolname = ''LongAccount''
	, @businessunit = @businessUnit
	, @businessunitalias = ''ial''
	, @periodends = null
	, @periodendsalias = ''a''
	, @excludecompanies = @excludeCompanies
	, @filterClause = @uomWhere output

	if ( len(@branchplant) > 0 ) begin
		if ( len(@uomWhere) > 0 ) set @uomWhere = @uomWhere + '' AND ''
		set @uomWhere = @uomWhere + ''BranchPlant = '''''' + @branchplant + ''''''''
	end

	if ( len(@uomWhere) > 0 ) begin
		set @sql = @sql + ''
			WHERE (periodends = '''''' + convert(varchar,@periodends,101) + '''''' OR periodends = '''''' + convert(varchar,@lastPeriodEnd,101) + '''''')
				AND '' + @uomWhere
	end

	-- update conv factor
	set @sql = @sql + ''
			update @conversions
				set ConversionFactor = dbo.Convert_Primary_UOM(ConverterBranchPlant,ConverterShortItem,ConverterUOM,ConverterCommonUOM)''
end

set @sql = @sql + ''

''
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
-- run query
---------------------------------------------------------------------------------------
-- opening balance, common uom and items
exec usp2GetStandardFilters
	@companynumber=@companyNumber
, @companynumberalias = ''a''
, @accountnumber = @accountNumber
, @accountnumberalias = ''a''
, @accountnumbercolname = ''LongAccount''
, @businessunit = @businessUnit
, @businessunitalias = ''ial''
, @periodends = @lastPeriodEnd
, @periodendsalias = ''a''
, @excludecompanies = @excludeCompanies
, @filterClause = @openWhere output

if ( len(@branchplant) > 0 ) begin
	if ( len(@openWhere) > 0 ) set @openWhere = @openWhere + '' AND ''
	set @openWhere = @openWhere + ''a.BranchPlant = '''''' + @branchplant + ''''''''
end

set @qry = @qry +  ''
from	(
select sum(isnull(a.'' + @startEndValueCol + '',0)) as Opening
			,ItemNumber as ILLITM
			,converter.conversionfactor
		from dbo.RInvAsOf a
			join dbo.RInvAccountList ial on a.LongAccount = ial.longaccount
			join dbo.F4101 mstr on a.ItemNumber = mstr.IMLITM
			left join (select * from @conversions) converter
									on converter.ConverterBranchPlant = a.BranchPlant
									and converter.ConverterShortItem = mstr.IMITM
									and converter.ConverterUOM = mstr.IMUOM1
		where 
			'' + @openWhere + ''		
		group by ItemNumber,ConversionFactor
	) openbal
	left join dbo.F4101 itm on openbal.illitm = itm.IMLITM ''

---------------------------------------------------------------------------------------
-- user columns
declare mvCols_cur cursor
for 
	select columntitle,columnfield,columncode1,columncode2,columncode3,columncode4,columncode5,columncode6
	from dbo.RMovementColumn
	order by ColumnSort
open mvCols_cur

fetch next from mvCols_cur
	into @colTitle,@colField,@colCode1,@colCode2,@colCode3,@colCode4,@colCode5,@colCode6

while @@fetch_status = 0 
Begin
	set @codes = ''''

	-- get codes
	if ( len(isnull(@colCode1,'''')) > 0 ) begin
		set @codes = @codes + '''''''' + @colCode1 + '''''''' + '',''
	end
	if ( len(isnull(@colCode2,'''')) > 0 ) begin
		set @codes = @codes + '''''''' + @colCode2 + '''''''' + '',''
	end
	if ( len(isnull(@colCode3,'''')) > 0 ) begin
		set @codes = @codes + '''''''' + @colCode3 + '''''''' + '',''
	end
	if ( len(isnull(@colCode4,'''')) > 0 ) begin
		set @codes = @codes + '''''''' + @colCode4 + '''''''' + '',''
	end
	if ( len(isnull(@colCode5,'''')) > 0 ) begin
		set @codes = @codes + '''''''' + @colCode5 + '''''''' + '',''
	end
	if ( len(isnull(@colCode6,'''')) > 0 ) begin
		set @codes = @codes + '''''''' + @colCode6 + '''''''' + '',''
	end

	-- remove trailing ,
	if ( len(@codes) > 0 ) begin
		set @codes = substring(@codes,0,len(@codes))
	end






			-- build query
		If @idx Between 0 and 15
		Begin
			set @qry = @qry + ''
			left join (
				select 
					 sum(isnull(a.'' + @movValueCol + '',0)) as Value			
					,illitm
				from dbo.f4111b a
					join dbo.RInvAccountList ial on a.inventoryaccount = ial.longaccount
				where '' + @colField + '' IN ('' + @codes + '')
					'' + @WHERE + ''
				group by illitm
			) col'' + cast(@idx as varchar) + '' on openbal.ILLITM = col'' + cast(@idx as varchar) + ''.illitm''

			-- cols to select
			set @selCols = @selCols + ''
				,case isnull(conversionfactor,1) when 0 then 0 when 1 then isnull(col'' + cast(@idx as varchar) + ''.value,0) else isnull(cast((col'' + cast(@idx as varchar) + ''.value / openbal.ConversionFactor) as DECIMAL(18, 2)),0) end as ['' + @colTitle + '']''
			set @varcalc  = @varcalc + '' + isnull(col'' + cast(@idx as varchar) + ''.value,0)''
		End

		If @idx > 15
		Begin
			set @qry2 = @qry2 + ''
			left join (
				select 
					 sum(isnull(a.'' + @movValueCol + '',0)) as Value			
					,illitm
				from dbo.f4111b a
					join dbo.RInvAccountList ial on a.inventoryaccount = ial.longaccount
				where '' + @colField + '' IN ('' + @codes + '')
					'' + @WHERE + ''
				group by illitm
			) col'' + cast(@idx as varchar) + '' on openbal.ILLITM = col'' + cast(@idx as varchar) + ''.illitm''

			-- cols to select
			set @selCols = @selCols + ''
				,case isnull(conversionfactor,1) when 0 then 0 when 1 then isnull(col'' + cast(@idx as varchar) + ''.value,0) else isnull(cast((col'' + cast(@idx as varchar) + ''.value / openbal.ConversionFactor) as DECIMAL(18, 2)),0) end as ['' + @colTitle + '']''
			set @varcalc  = @varcalc + '' + isnull(col'' + cast(@idx as varchar) + ''.value,0)''
		End


	-- next column
	set @idx = @idx + 1
	fetch next from mvCols_cur
		into @colTitle,@colField,@colCode1,@colCode2,@colCode3,@colCode4,@colCode5,@colCode6

end

close mvCols_cur
deallocate mvCols_cur



---------------------------------------------------------------------------------------
-- closing bal
exec usp2GetStandardFilters
	@companynumber=@companyNumber
, @companynumberalias = ''a''
, @accountnumber = @accountNumber
, @accountnumberalias = ''a''
, @accountnumbercolname = ''LongAccount''
, @businessunit = @businessUnit
, @businessunitalias = ''ial''
, @periodends = @periodEnds
, @periodendsalias = ''a''
, @excludecompanies = @excludeCompanies
, @filterClause = @closeWhere output

if ( len(@branchplant) > 0 ) begin
	if ( len(@closeWhere) > 0 ) set @closeWhere = @closeWhere + '' AND ''
	set @closeWhere = @closeWhere + ''BranchPlant = '''''' + @branchplant + ''''''''
end

set @qryClose = @qryClose + ''
	left join (
		select sum(isnull(a.'' + @startEndValueCol + '',0)) as closingBal
			,ItemNumber as ILLITM
		from dbo.RInvAsOf a
			join dbo.RInvAccountList ial on a.LongAccount = ial.longaccount
		where 
			'' + @closeWhere + ''
		group by ItemNumber
	) closing on openbal.ILLITM = closing.illitm''

---------------------------------------------------------------------------------------
-- execute
set @CommonUOM = isnull(@CommonUOM,'''')

if ( @debug = 1 ) Begin
print @sql + ''''
print ''select
	openbal.ILLITM as Item
	,itm.IMDSC1 as [Description]
	, case isnull(openbal.ConversionFactor,-1) when -1 then itm.IMUOM1 else '''''' + @CommonUOM + '''''' end as UOM
	,isnull(openbal.ConversionFactor,1) as ConversionFactor
	,case isnull(conversionfactor,1) when 0 then 0 when 1 then isnull(openbal.Opening,0) else isnull((openbal.Opening / openbal.ConversionFactor),0) end as [Opening Balance] 
	'' + @selCols + ''
	,case isnull(conversionfactor,1) when 0 then 0 when 1 then isnull(closing.closingBal,0) else isnull((closing.closingBal / openbal.ConversionFactor),0) end as [Closing Balance] 
	,case isnull(conversionfactor,1) 
		when 0 then 0 
		when 1 then abs(( ('' + @varCalc + '') - isnull(closing.ClosingBal,0) ))
	  else abs(( (('' + @varCalc + '') - isnull(closing.ClosingBal,0)) / openbal.ConversionFactor) )
	 end as Variance''
print @qry + '' ''
print @qry2 + '' ''
print @qryClose + '' ''
print ''order by Item''

End

exec (@sql + ''select
	openbal.ILLITM as Item
	,itm.IMDSC1 as [Description]
	, case isnull(openbal.ConversionFactor,-1) when -1 then itm.IMUOM1 else '''''' + @CommonUOM + '''''' end as UOM
	,isnull(openbal.ConversionFactor,1) as ConversionFactor
	,case isnull(conversionfactor,1) when 0 then 0 when 1 then isnull(openbal.Opening,0) else isnull((openbal.Opening / openbal.ConversionFactor),0) end as [Opening Balance] 
	'' + @selCols + ''
	,case isnull(conversionfactor,1) when 0 then 0 when 1 then isnull(closing.closingBal,0) else isnull((closing.closingBal / openbal.ConversionFactor),0) end as [Closing Balance] 
	,cast( (case isnull(conversionfactor,1) 
		when 0 then 0 
		when 1 then abs(( ('' + @varCalc + '') - isnull(closing.ClosingBal,0) ))
	  else abs(( (('' + @varCalc + '') - isnull(closing.ClosingBal,0)) / openbal.ConversionFactor) )
	 end) as integer) as Variance
'' + @qry + @qry2 + @qryClose + ''
	order by Item'')

set nocount off' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetMovementsReport] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetObjectAccounts]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetObjectAccounts]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  StoredProcedure [dbo].[usp2GetObjectAccounts]    Script Date: 10/29/2007 19:58:36 ******/
CREATE   PROCEDURE [dbo].[usp2GetObjectAccounts]
 @excludeCompanies varchar(255) = null
AS
/*

	exec usp2getobjectaccounts
	 
*/
	set nocount on

	declare @excComps table (companynumber varchar(30) primary key)
	insert @excComps select * from dbo.fn_SplitString(@excludeCompanies,'','')


	if ( @excludeCompanies is not null ) begin
		SELECT		distinct LongAccount as ObjectAccount, AccountDescription, a.companynumber
		FROM			RInvAccountList a
		Inner Join		RCompanies C On A.CompanyNumber = C.CompanyNumber
		WHERE			objectaccount is not null 
							--and rtrim(objectaccount) != ''''
							and a.companynumber not in (select companynumber from @excComps)
		ORDER BY	A.CompanyNumber, LongAccount
	end
	else begin
		SELECT		distinct LongAccount as ObjectAccount, AccountDescription, a.companynumber
		FROM			RInvAccountList a
		Inner Join		RCompanies C On A.CompanyNumber = C.CompanyNumber
		WHERE			objectaccount is not null 
							--and rtrim(objectaccount) != ''''
		ORDER BY	A.CompanyNumber, LongAccount
	end
	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetObjectAccounts] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetOutOfBalance]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetOutOfBalance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2GetOutOfBalance] (
	 @companyNumber varchar(5) = ''''
	,@accountnumber varchar(28) = ''''
	,@businessunit varchar(12) = ''''
	,@excludeCompanies varchar(255) = null
	,@debug bit = 0
) AS
/*
	exec usp2GetOutOfBalance 
	exec usp2GetOutOfBalance @companynumber = ''00134''
	exec usp2GetOutOfBalance @companynumber = ''00135''

*/
	set nocount on

	declare @maxpe datetime
	select @maxpe = max(periodends) from rinvaccountsummary
	
	declare @sql nvarchar(4000)
	declare @where nvarchar(2000)

	set @sql = ''''
	set @where = ''''

	exec usp2GetStandardFilters
		  @companynumber=@companyNumber
		, @companynumberalias = ''al''
		, @accountnumber = @accountNumber
		, @accountnumberalias = ''al''
		, @accountnumbercolname = ''longaccount''
		, @businessunit = @businessUnit
		, @businessunitalias = ''al''
		, @periodends = null
		, @periodendsalias = ''ias''
		, @excludecompanies = @excludeCompanies
		, @filterClause = @where output
		

	set @sql = @sql + ''
		select 
			 PeriodEnds
			,sum(outofbalance) as [Out Of Balance]
		from rinvaccountsummary ias
			inner join rcompanies c on ias.companynumber = c.companynumber
			INNER JOIN rinvaccountlist al ON ias.longaccount = al.longaccount AND ias.companynumber = al.companynumber
		where periodends > dateadd(m,-24,'''''' + CONVERT(varchar,@maxpe,120) + '''''')''

	if ( len(@where) > 0 ) begin
		set @sql = @sql + ''
			AND '' + @where
	end

	set @sql = @sql + ''			
		group by periodends
		order by periodends''
		
	if ( @debug = 1 ) print isnull(@sql,''null query'')
	exec sp_executeSQL @sql

  set nocount off

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetOutOfBalance] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetPeriodCloseOutOfBalance]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetPeriodCloseOutOfBalance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

CREATE    Procedure [dbo].[usp2GetPeriodCloseOutOfBalance](
	 @companyNumber varchar(5) = ''''
	,@accountnumber varchar(28) = ''''
	,@businessunit varchar(12) = ''''
	,@periodends smalldatetime = null
	,@excludeCompanies varchar(255) = null
	,@debug bit = 0
) AS
/*
	exec usp2GetPeriodCloseOutOfBalance
		@companynumber=''01111''
		--,@accountnumber=''11111000.1351  .000     ''
		--@businessunit = ''    11961000''
		,@periodends = ''3/31/07''
		,@debug =1

	exec usp2GetPeriodCloseOutOfBalance
		@companynumber=''01140''
		--,@accountnumber=''11111000.1351  .000     ''
		--@businessunit = ''    11961000''
		,@periodends = ''01/31/07''
		,@debug =1

select * from rinvaccountlist where companynumber = ''01111''
select * from v_last_elapsed_period_end

select .2 / 1606001.79
*/
	set nocount on
	declare @sql nvarchar(4000)
	declare @where varchar(1024)

	-- select
	set @sql = ''select --a.companynumber, 
					isnull(abs(sum(amountonhand)),0) as perpetual, 
					isnull(abs(sum(outofbalance)),0) as oob,
					isnull(case sum(amountonhand) when 0 then case sum(outofbalance) when 0 then 0 else -9999 end else abs(sum(outofbalance))/abs(sum(amountonhand)) end,0) as per
		from rinvaccountsummary a
		inner join rcompanies c on a.companynumber = c.companynumber
			left join RInvAccountList al on a.longaccount = al.longaccount''
/*
			inner join v_last_elapsed_period_end b on a.companynumber = b.companynumber and a.periodends = b.periodends''
*/
	-- where
	exec usp2GetStandardFilters
		@companynumber=@companyNumber
	, @companynumberalias = ''a''
	, @accountnumber = @accountnumber
	, @accountnumberalias = ''a''
	, @accountnumbercolname = ''longaccount''
	, @businessunit = @businessunit
	, @businessunitalias = ''al''
	, @periodends = @periodends
	, @periodendsalias = ''a''
	, @excludecompanies = @excludeCompanies
	, @filterClause = @where output
	
	if ( len(@where) > 0 ) begin
		set @sql = @sql + '' 
		WHERE '' + @where
	end
	
	if ( @debug = 1 ) print ''['' + @sql + '']''
	exec sp_executeSQL @sql

	set nocount off

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetPeriodCloseOutOfBalance] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetPeriodEndClose]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetPeriodEndClose]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create    Procedure [dbo].[usp2GetPeriodEndClose](
	 @companyNumber varchar(5) = ''''
	,@accountnumber varchar(28) = ''''
	,@businessunit varchar(12) = ''''
	,@periodends smalldatetime = null
	,@excludeCompanies varchar(255) = null
) AS
/*
	exec uspGetPeriodEndClose ''00117'',''00121,00122''

select * from v_last_elapsed_period_end
*/
	set nocount on

	if ( @companynumber = '''' ) begin
		set @companynumber = ''%''
	end

	if ( @excludecompanies is null ) begin
		select max(periodends) as periodends 
		from v_last_elapsed_period_end
		where companynumber like @companynumber
	end
	else begin
		select max(periodends) as periodends 
		from v_last_elapsed_period_end
		where companynumber like @companynumber
			and CompanyNumber not in (select * from dbo.fn_SplitString(@excludeCompanies,'',''))
	end	

	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetPeriodEndClose] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetPeriodEnds]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetPeriodEnds]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE   PROCEDURE [dbo].[usp2GetPeriodEnds]
AS
/*
	exec usp2getperiodends
*/
	set nocount on

    SELECT  CONVERT(VARCHAR(8), PeriodEnds, 1) AS PeriodEnds
    FROM    RInvAccountSummary A
	Inner Join RCompanies c On A.CompanyNumber = C.CompanyNumber
    GROUP BY PeriodEnds
    ORDER BY CONVERT(DATETIME, PeriodEnds, 1)

	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetPeriodEnds] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetRCardexLedgerCompare]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetRCardexLedgerCompare]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[usp2GetRCardexLedgerCompare]
	 @companyNumber varchar(5) = ''''
	,@accountnumber varchar(28) = ''''
	,@businessunit varchar(12) = ''''
	,@periodends smalldatetime = null
	,@excludeCompanies varchar(255) = null
	,@WithNotes bit = 0
	,@debug bit = 0
As

	set nocount on

	declare @sql nvarchar(4000)
	declare @where varchar(1024)

	-- select
	set @sql = ''SELECT top 65000
			TransDate,
			isnull(note.Worked,0) as Worked,
			isnull(note.Note,'''''''') as Note,
			clc.CompanyNumber AS Company,
            clc.PeriodEnds,
            clc.InventoryAccount AS Account,
            al.BusinessUnit As BU,
			al.ObjectAccount As Object,
            RTRIM(clc.DocType) AS DT,
            clc.DocNumber,
            RTRIM(clc.OrderType) AS OT,
			--wasrst as ''''WO Sts'''',
            CardexLedgerVariance,
						Status,
            LTRIM(Comment) AS Comment,
            CAST(clc.MfgBatch AS Integer) AS ''''Mfg Batch'''',
            CardexAmount,
            LedgerAmount,
			MatchingDocument,
			MatchingType,
            LTRIM(al.BusinessUnit) AS BusinessUnit,
            al.ObjectAccount''
	if ( @WithNotes = 1 ) begin
		set @sql = @sql + ''
		FROM    RCardexLedgerCompare2WorkNote note
			inner join RCardexLedgerCompare2 clc 
							on clc.companynumber = note.companynumber
							and clc.inventoryaccount = note.inventoryaccount
							and clc.ordertype = note.ordertype
							and clc.doctype = note.doctype
							and clc.docnumber = note.docnumber
							and clc.periodends = note.periodends
							and clc.mfgbatch = note.mfgbatch
			INNER JOIN RCompanies c On (note.CompanyNumber = c.CompanyNumber)
			INNER JOIN rinvaccountlist al
							ON clc.inventoryaccount = al.longaccount AND clc.companynumber = al.companynumber''
			--left join vcr_F4801 on clc.companynumber = waco and clc.ordertype = wadcto and clc.matchingdocument = wadoco''
	end
	else begin
		set @sql = @sql + ''
		FROM    RCardexLedgerCompare2 clc 
			INNER JOIN rinvaccountlist al
							ON clc.inventoryaccount = al.longaccount AND clc.companynumber = al.companynumber
			INNER JOIN RCompanies c On (al.CompanyNumber = c.CompanyNumber)
			--left join vcr_F4801 on clc.companynumber = waco and clc.ordertype = wadcto and clc.matchingdocument = wadoco
			left join RCardexLedgerCompare2WorkNote note
							on clc.companynumber = note.companynumber
							and clc.inventoryaccount = note.inventoryaccount
							and clc.ordertype = note.ordertype
							and clc.doctype = note.doctype
							and clc.docnumber = note.docnumber
							and clc.periodends = note.periodends
							and clc.mfgbatch = note.mfgbatch''
	end

	-- where
	exec usp2GetStandardFilters
		@companynumber=@companyNumber
	, @companynumberalias = ''clc''
	, @accountnumber = @accountNumber
	, @accountnumberalias = ''clc''
	, @accountnumbercolname = ''inventoryaccount''
	, @businessunit = @businessUnit
	, @businessunitalias = ''al''
	, @periodends = @periodends
	, @periodendsalias = ''clc''
	, @excludecompanies = @excludeCompanies
	, @filterClause = @where output
	
	if ( len(@where) > 0 ) begin
		set @sql = @sql + '' 
		WHERE '' + @where
	end
	
	-- order by
  set @sql = @sql +  '' 
	ORDER BY clc.companynumber,
			 transDate DESC,
			 clc.doctype''

	if ( @debug = 1 ) print ''['' + @sql + '']''
	exec sp_executeSQL @sql

set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetRCardexLedgerCompare] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetRInvAccountSummary]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetRInvAccountSummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2GetRInvAccountSummary]	
	 @companyNumber varchar(5) = ''''
	,@accountnumber varchar(28) = ''''
	,@businessunit varchar(12) = ''''
	,@periodends smalldatetime = null
	,@excludeCompanies varchar(255) = null
	,@debug bit = 0
As
/*
	exec [dbo].[usp2GetRInvAccountSummary] 
	 --@companynumber=''01002''
	--@accountnumber=''102900001.116120''
	--@businessunit = ''    13043000''
	--,@periodends=''3/31/2007''
	@debug = 1

select * from rinvaccountlist
*/
	set nocount on

	declare @sql nvarchar(4000)
	declare @where varchar(1024)
	set @sql = ''''
	set @where = ''''

/* first 3 cols must be comp,account,pe */
	set @sql = @sql + ''
  SELECT  ias.CompanyNumber AS Company,
		  Ltrim(al.BusinessUnit) As [B/U],
		  Ltrim(al.ObjectAccount) As [Object],
          ias.LongAccount AS Account,
          PeriodEnds AS [P/E],
          BeginningBalance AS [Beg Bal],
          PeriodGL AS [Per GL],
          EndingGLBalance AS [End GL Bal],
          GLRollOK AS [GL OK?],
          UnpostedBatchAmount AS [Unpst GL],
          AmountonHand AS [Perpetual],
          AccountVariance AS [Beg Var],
          PeriodUnpostedCardex AS [EndofDay],
          TransactionVariance AS [Variance],
          JournalEntries AS [JEs],
          OutofBalance AS [Out of Bal],
          BalCXVar AS [Item Roll],
          OOBRollOK AS [Var OK?],
          LTRIM(al.BusinessUnit) AS BusinessUnit,
          al.ObjectAccount
  FROM    RInvAccountSummary ias 
  INNER JOIN RCompanies c On (ias.CompanyNumber = c.CompanyNumber)
  INNER JOIN rinvaccountlist al
          ON ias.longaccount = al.longaccount AND
             ias.companynumber = al.companynumber''
	-- where
	exec usp2GetStandardFilters
		@companynumber=@companyNumber
	, @companynumberalias = ''ias''
	, @accountnumber = @accountNumber
	, @accountnumberalias = ''ias''
	, @accountnumbercolname = ''longaccount''
	, @businessunit = @businessUnit
	, @businessunitalias = ''al''
	, @periodends = @periodends
	, @periodendsalias = ''ias''
	, @excludecompanies = @excludeCompanies
	, @filterClause = @where output
	
	if ( len(@where) > 0 ) begin
		set @sql = @sql + '' 
		WHERE '' + @where
	end
	
	-- order by
  set @sql = @sql +  '' 
  ORDER BY ias.CompanyNumber,
          ias.LongAccount,
          ias.PeriodEnds,
          ias.GLRollOK,
          ABS(ias.AmountonHand) DESC''

	if ( @debug = 1 ) print ''['' + @sql + '']''
	exec sp_executeSQL @sql

	set nocount off

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetRInvAccountSummary] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetRPerpetualInv]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetRPerpetualInv]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
Create PROCEDURE [dbo].[usp2GetRPerpetualInv]
             @companyNumber varchar(5) = ''''
			,@accountnumber varchar(28) = ''''
			,@businessunit varchar(12) = ''''
			,@periodends smalldatetime = null
			,@excludeCompanies varchar(255) = null
			,@AOHThreshold int = null
			,@CommonUOM char(2) = null
			,@SummarizeByItem char(1) = ''N''
			,@debug bit = 1
			
AS 

	set nocount on

	declare @sql nvarchar(4000)
	declare @where nvarchar(2000)
	declare @orderby nvarchar(2000)

	set @sql = ''''
	set @where = ''''
	set @orderby = ''''

	-- lookup aoh if requested
	if ( @AOHThreshold = -9999 ) begin	set @AOHThreshold = ( SELECT Threshold1 FROM RConstants) end
	if ( @CommonUOM = '''' ) begin set @CommonUOM = null	end
	


	
---------------------------------------------------------------------------------------------------------------------------------------------------------
-- set up and populate conversion factor table for common units of measure
if ( @CommonUOM is not null ) begin
	set @sql = @sql + ''declare @conversions table (
						ConverterBranchPlant varchar(12)
						,ConverterShortItem decimal(8,0)
						,ConverterUOM char(2)
						,ConverterCommonUOM char(2)
						,ConversionFactor decimal (18,6)
		Primary Key (ConverterBranchPlant,ConverterShortItem,ConverterUOM,ConverterCommonUOM)
	)''


	if ( @periodends is null ) 
begin
		set @sql = @sql + ''
			insert @conversions(ConverterBranchPlant,ConverterShortItem,ConverterUOM,ConverterCommonUOM)
			select distinct branchplant,shortitem,UnitOfMeasure As UOM,'''''' + @CommonUOM + ''''''
				FROM    dbo.RPerpetualInv rpi
				Inner Join RCompanies c On (rpi.CompanyNumber = c.CompanyNumber) 
				inner Join dbo.RInvAccountList al on rpi.longaccount = al.longaccount ''

		exec usp2GetStandardFilters
			@companynumber=@companyNumber
			, @companynumberalias = ''rpi''
			, @accountnumber = @accountNumber
			, @accountnumberalias = ''rpi''
			, @accountnumbercolname = ''longaccount''
			, @businessunit = @businessUnit
			, @businessunitalias = ''al''
			, @periodends = @periodends
			, @periodendsalias = ''''
			, @excludecompanies = @excludeCompanies
			, @filterClause = @where output

end
	
	else 
begin
		set @sql = @sql + ''
			insert @conversions(ConverterBranchPlant,ConverterShortItem,ConverterUOM,ConverterCommonUOM)
			select distinct branchplant,shortitem,UnitOfMeasure As UOM,'''''' + @CommonUOM + ''''''
				FROM    dbo.RInvAsOf iao
				INNER JOIN RCompanies c On (iao.CompanyNumber = c.CompanyNumber)
				left join dbo.rperpetualinv rpi
							on iao.companynumber = rpi.companynumber
							and iao.longaccount = rpi.longaccount
							and iao.branchplant = rpi.branchplant
							and iao.shortitem = rpi.shortitem
							and iao.itemnumber = rpi.itemnumber
							and iao.location = rpi.location
							and iao.lot = rpi.lot 
				inner join dbo.RInvAccountList al on iao.longaccount = al.longaccount ''


		exec usp2GetStandardFilters
			@companynumber=@companyNumber
			, @companynumberalias = ''iao''
			, @accountnumber = @accountNumber
			, @accountnumberalias = ''iao''
			, @accountnumbercolname = ''longaccount''
			, @businessunit = @businessUnit
			, @businessunitalias = ''al''
			, @periodends = @periodends
			, @periodendsalias = ''iao''
			, @excludecompanies = @excludeCompanies
			, @filterClause = @where output
end
	
	if ( len(@where) > 0 ) 
begin
		set @sql = @sql + ''	WHERE '' + @where
end

	-- update conv factor
	set @sql = @sql + ''
			update @conversions	set ConversionFactor = dbo.Convert_Primary_UOM(ConverterBranchPlant,ConverterShortItem,ConverterUOM,ConverterCommonUOM)''

	set @sql = @sql + ''	''

end




---------------------------------------------------------------------------------------------------------------------------------------------------------
-- No Period Ends, not summarized
/* NOTE col order is expected as follows Branch: 3	ItemNumber:	4 Location:	5	Lot: 6 */

	if ( @periodends is null ) 
begin

	if ( @SummarizeByItem = ''N'' ) 
begin

			set @sql = @sql + ''
								SELECT  
								LTRIM(RTRIM(rpi.CompanyNumber)) AS Company,
								rpi.LongAccount,
								LTRIM(BranchPlant) AS Branch,
								ShortItem,
								ItemNumber,
								ItemDescription,
								AmountonHand,
								Location,
								Lot,
								GLClass,
								--SalesCategory01Code ,
								--SalesCategory02Code ,
								--SalesCategory03Code ,
								--SalesCategory04Code ,
								--SalesCategory05Code ,
								--SalesCategory06Code ,
								--SalesCategory07Code ,
								--SalesCategory08Code ,
								--SalesCategory09Code ,
								--SalesCategory10Code ,
								--PurchasingCategory01Code ,
								--PurchasingCategory02Code ,
								--PurchasingCategory03Code ,
								--PurchasingCategory04Code ,
								--PurchasingCategory05Code ,
								--PurchasingCategory06Code ,
								--PurchasingCategory07Code ,
								--PurchasingCategory08Code ,
								--PurchasingCategory09Code ,
								--PurchasingCategory10Code ,
								UnitofMeasure AS UOM,
								rpi.QuantityonHand AS QOH,
								UnitCost as Cost,''
	if ( @CommonUOM is not null ) 
begin
			set @sql = @sql + ''
								'''''' + @commonuom + '''''' as ComUOM,
								case when conversionfactor = 0 then 0 else cast((rpi.QuantityonHand / converter.ConversionFactor) as DECIMAL(18, 2)) end as ComQOH,
								cast((UnitCost * converter.ConversionFactor) as decimal(18,6)) as ComCost,
								ConversionFactor,''
end
			set @sql = @sql + ''
								StockingType AS ST,
								CostMethod AS CM,
								Material,
								Labor,
								Overhead,
								CASE WHEN CostMethod = ''''07'''' AND ABS(UnitCost - CONVERT(DECIMAL(18, 2), ( Material + Labor + Overhead ))) > .01 THEN ''''*'''' ELSE '''''''' END AS CI,
								BaselineVar AS AmountVar,
								EstUnits AS QuantityVar,
								al.BusinessUnit AS BusinessUnit,
								al.ObjectAccount''
			
			-- from
			set @sql = @sql + ''
								FROM    dbo.RPerpetualInv rpi
								INNER JOIN RCompanies c On (rpi.CompanyNumber = c.CompanyNumber) 
								INNER JOIN dbo.rinvaccountlist al ON rpi.longaccount = al.longaccount AND al.companynumber = rpi.companynumber''

	if ( @CommonUOM is not null ) 
begin
			set @sql = @sql + ''
								Left Join (select * from @conversions) converter
											on converter.ConverterBranchPlant = rpi.branchplant
											and converter.ConverterShortItem = rpi.shortitem
											and converter.ConverterUOM = rpi.UnitofMeasure
											and converter.ConverterCommonUOM = '''''' + @CommonUOM + ''''''''
end		
		
			-- where
			set @sql = @sql + '' 
								WHERE ( rpi.QuantityonHand <> 0 OR ABS(AmountOnHand) >= .05 OR ABS(BaselineVar) > .05)''
			
	if ( len(@where) = 0 ) 
begin
				exec usp2GetStandardFilters
					@companynumber=@companyNumber
					, @companynumberalias = ''rpi''
					, @accountnumber = @accountNumber
					, @accountnumberalias = ''rpi''
					, @accountnumbercolname = ''longaccount''
					, @businessunit = @businessUnit
					, @businessunitalias = ''al''
					, @periodends = @periodends
					, @periodendsalias = ''''
					, @excludecompanies = @excludeCompanies
					, @filterClause = @where output
end
	
	if ( len(@where) > 0 ) 
begin
			set @sql = @sql + ''	AND '' + @where
end

end


---------------------------------------------------------------------------------------------------------------------------------------------------------
-- No Period Ends, summarized
else begin

			set @sql = @sql + ''
								SELECT * FROM (SELECT  LTRIM(RTRIM(rpi.CompanyNumber)) AS Company,
								rpi.LongAccount,
								LTRIM(BranchPlant) AS Branch,
								ShortItem,
								ItemNumber,
								ItemDescription,
								Sum(AmountonHand) as AmountOnHand,
								UnitofMeasure AS UOM,
								Sum(rpi.QuantityonHand) AS QOH,
								MAX(UnitCost) as Cost,''

	if ( @CommonUOM is not null ) 
begin
			set @sql = @sql + ''
								'''''' + @commonuom + '''''' as ComUOM,
								case when conversionfactor = 0 then 0 else cast((Sum(rpi.QuantityonHand) / ConversionFactor) as DECIMAL(18, 2)) end as ComQOH,
								cast((Max(UnitCost) * converter.ConversionFactor) as decimal(18,6)) as ComCost,
								ConversionFactor,''
								
end

			set @sql = @sql + ''
								Sum(BaselineVar) AS AmountVar,
								Sum(EstUnits) AS QuantityVar,
								al.BusinessUnit AS BusinessUnit,
								al.ObjectAccount''
			-- from
			set @sql = @sql + ''
								FROM    dbo.RPerpetualInv rpi
								INNER JOIN RCompanies c On (rpi.CompanyNumber = c.CompanyNumber) 
								INNER JOIN dbo.rinvaccountlist al ON rpi.longaccount = al.longaccount AND al.companynumber = rpi.companynumber''

	if ( @CommonUOM is not null ) 
begin
			set @sql = @sql + ''
								left join (select * from @conversions) converter
										on converter.ConverterBranchPlant = rpi.branchplant
										and converter.ConverterShortItem = rpi.shortitem
										and converter.ConverterUOM = rpi.UnitofMeasure
										and converter.ConverterCommonUOM = '''''' + @CommonUOM + ''''''''
end		
			
			-- inner where			
	if ( len(@where) = 0 ) 
begin
				exec usp2GetStandardFilters
					@companynumber=@companyNumber
					, @companynumberalias = ''rpi''
					, @accountnumber = @accountNumber
					, @accountnumberalias = ''rpi''
					, @accountnumbercolname = ''longaccount''
					, @businessunit = @businessUnit
					, @businessunitalias = ''al''
					, @periodends = @periodends
					, @periodendsalias = ''''
					, @excludecompanies = @excludeCompanies
					, @filterClause = @where output
end
	
	if ( len(@where) > 0 ) 
begin
			set @sql = @sql + ''
										WHERE '' + @where
end
			
			-- group by
			set @sql = @sql + ''
										Group by rpi.CompanyNumber,rpi.LongAccount,BranchPLant,ItemNumber,ItemDescription,UnitofMeasure,BusinessUnit,ObjectAccount,ShortItem''
	if ( @CommonUOM is not null ) 
begin
				
			set @sql = @sql + ''			,ConversionFactor''
end

			-- finish inner query
			set @sql = @sql + ''			) a''

			-- outer where
			set @sql = @sql + '' 
										WHERE ( QOH <> 0 OR Abs(AmountVar) > .05 OR ABS(AmountOnHand) >= .05)''

end -- item summ
end -- p/e



---------------------------------------------------------------------------------------------------------------------------------------------------------
-- Period Ends, Not summarized
/* NOTE col order is expected as follows Branch: 4 ItemNumber: 5 Location: 7 Lot: 8	QOH: 10	HasMissing:15 */
else begin -- p/e branch

	if ( @SummarizeByItem = ''N'' ) 
begin
			set @sql = @sql + ''
										SELECT  
										iao.CompanyNumber AS Company,
										iao.PeriodEnds,
										iao.LongAccount,
										LTRIM(iao.BranchPlant) AS Branch,
										iao.ShortItem,
										iao.ItemNumber,
										IMDSC1 As ItemDescription,
										iao.Location,
										iao.Lot,
										iao.GLClass,
										--SalesCategory01Code ,
										--SalesCategory02Code ,
										--SalesCategory03Code ,
										--SalesCategory04Code ,
										--SalesCategory05Code ,
										--SalesCategory06Code ,
										--SalesCategory07Code ,
										--SalesCategory08Code ,
										--SalesCategory09Code ,
										--SalesCategory10Code ,
										--PurchasingCategory01Code ,
										--PurchasingCategory02Code ,
										--PurchasingCategory03Code ,
										--PurchasingCategory04Code ,
										--PurchasingCategory05Code ,
										--PurchasingCategory06Code ,
										--PurchasingCategory07Code ,
										--PurchasingCategory08Code ,
										--PurchasingCategory09Code ,
										--PurchasingCategory10Code ,
										IMUOM1 as UOM,
										case when uom.ItemNumber IS NULL then CONVERT(DECIMAL(18, 2), iao.QuantityonHand)else -9999	end as QOH,
										--isnull(rpi.UnitCost, 0) as CurrCost,''

	if ( @CommonUOM is not null ) 
begin
				set @sql = @sql + ''
										'''''' + @commonuom + '''''' as ComUOM,
										case when uom.ItemNumber IS NULL then case when converter.ConversionFactor = 0 then 0 else CONVERT(DECIMAL(18, 2), (iao.QuantityOnHand / converter.ConversionFactor) ) end else -9999	end as ComQOH,
										cast(isnull(rpi.UnitCost,0) * converter.ConversionFactor as decimal(18,6)) as ComCost,
										converter.ConversionFactor,''
end

				set @sql = @sql + ''
										iao.AmountonHand,
										al.BusinessUnit AS BusinessUnit,
										al.ObjectAccount,
										case when uom.ItemNumber IS NULL then ''''N'''' else ''''Y'''' end as HasMissingConversion''

			-- from
				set @sql = @sql + ''
										FROM  dbo.RInvAsOf iao With (Index(RInvAsOf_Period))
										INNER JOIN RCompanies c On (iao.CompanyNumber = c.CompanyNumber) 
										INNER JOIN dbo.rinvaccountlist al ON iao.longaccount = al.longaccount
										left join dbo.vcr_F4101	on iao.shortitem = imitm
										LEFT JOIN dbo.v_Integrity4_UOM_Conv uom	ON iao.ItemNumber = uom.ItemNumber''
	if ( @CommonUOM is not null ) 
begin
				set @sql = @sql + ''
										Left join (select * from @conversions) converter
											on converter.ConverterBranchPlant = iao.branchplant
											and converter.ConverterShortItem = iao.shortitem
											and converter.ConverterUOM = rpi.UnitofMeasure
											and converter.ConverterCommonUOM = '''''' + @CommonUOM + ''''''''
end	

			-- where
				set @sql = @sql + '' 
										WHERE ( iao.QuantityonHand <> 0 OR ABS(iao.AmountonHand) >= .05 )''
											
	if ( @AOHThreshold is not null ) 
begin
				set @sql = @sql + ''
										AND ( case when uom.ItemNumber IS NULL then CONVERT(DECIMAL(18, 2), iao.QuantityonHand) else -9999 end != 0 
										OR ABS(iao.AmountOnHand) >= .05)''
end 

	if ( len(@where) = 0 ) 
begin
				exec usp2GetStandardFilters
					@companynumber=@companyNumber
					, @companynumberalias = ''iao''
					, @accountnumber = @accountNumber
					, @accountnumberalias = ''iao''
					, @accountnumbercolname = ''longaccount''
					, @businessunit = @businessUnit
					, @businessunitalias = ''al''
					, @periodends = @periodends
					, @periodendsalias = ''iao''
					, @excludecompanies = @excludeCompanies
					, @filterClause = @where output
end

	if ( len(@where) > 0 ) 
begin
				set @sql = @sql + ''	AND '' + @where
end

end



---------------------------------------------------------------------------------------------------------------------------------------------------------
-- Period Ends, summarized
else begin
				set @sql = @sql + ''
										SELECT  
										a.Company,
										a.PeriodEnds,
										LongAccount,
										LTRIM(a.Branch) as Branch,
										a.ShortItem,
										a.ItemNumber,
										ItemDescription,
										UOM,
										case when uom.ItemNumber IS NULL then CONVERT(DECIMAL(18, 2), a.QuantityonHand)	else -9999 end as QOH,''

	if ( @CommonUOM is not null ) 
begin
				set @sql = @sql + ''
										'''''' + @commonuom + '''''' as ComUOM,
										case when uom.ItemNumber IS NULL
											then case when converter.ConversionFactor = 0 then 0 else CONVERT(DECIMAL(18, 2), (a.QuantityOnHand / converter.ConversionFactor) ) end
											else -9999
										end as ComQOH,
										cast(a.UnitCost * converter.ConversionFactor as decimal(18,6)) as ComCost,
										converter.ConversionFactor,''
end

				set @sql = @sql + ''
										AmountonHand,
										BusinessUnit,
										ObjectAccount,
										case when uom.ItemNumber IS NULL then ''''N'''' else ''''Y'''' end as HasMissingConversion''

				set @sql = @sql + ''
										FROM  (SELECT  
													iao.CompanyNumber AS Company,
													iao.PeriodEnds,
													iao.LongAccount,
													iao.BranchPlant AS Branch,
													iao.ItemNumber,
													iao.ShortItem,
													IMDSC1 As ItemDescription,
													sum(iao.QuantityOnHand) as QuantityonHand,
													IMUOM1 AS UOM,
													sum(iao.AmountonHand) as AmountOnHand,
													al.BusinessUnit AS BusinessUnit,
													al.ObjectAccount
											FROM    dbo.RInvAsOf iao With (Index(RInvAsOf_Period))
											INNER JOIN RCompanies c On (iao.CompanyNumber = c.CompanyNumber) 
											INNER JOIN dbo.rinvaccountlist al ON iao.longaccount = al.longaccount
											left join dbo.vcr_F4101 On (iao.ShortItem = IMITM)''

			-- inner where
	if ( len(@where) = 0 ) 
begin
				exec usp2GetStandardFilters
					@companynumber=@companyNumber
					, @companynumberalias = ''iao''
					, @accountnumber = @accountNumber
					, @accountnumberalias = ''iao''
					, @accountnumbercolname = ''longaccount''
					, @businessunit = @businessUnit
					, @businessunitalias = ''al''
					, @periodends = @periodends
					, @periodendsalias = ''iao''
					, @excludecompanies = @excludeCompanies
					, @filterClause = @where output
end

	if ( len(@where) > 0 ) 
begin
				set @sql = @sql +				''	WHERE '' + @where
end

			-- group by for item summarization
				set @sql = @sql + ''
												group by iao.CompanyNumber,iao.PeriodEnds,iao.LongAccount,iao.BranchPlant,iao.ItemNumber,IMDSC1,IMUOM1,BusinessUnit,ObjectAccount,iao.ShortItem''

			-- finish subquery, outer joins
				set @sql = @sql +				'')a	LEFT JOIN dbo.v_Integrity4_UOM_Conv uom	ON a.ItemNumber = uom.ItemNumber ''

	if ( @CommonUOM is not null ) 
begin
				set @sql = @sql + ''
												left join (select * from @conversions) converter
																		on converter.ConverterBranchPlant = a.branch
																		and converter.ConverterShortItem = a.shortitem
																		and converter.ConverterUOM = a.UOM
																		and converter.ConverterCommonUOM = '''''' + @CommonUOM + ''''''''
end

			-- outer where where
				set @sql = @sql + '' 
												WHERE ( a.QuantityonHand <> 0 OR ABS(a.AmountonHand) >= .05 )''
	if ( @AOHThreshold is not null ) 
begin
				set @sql = @sql + ''
												AND ( case when uom.ItemNumber IS NULL then CONVERT(DECIMAL(18, 2), a.QuantityonHand) else -9999 end != 0 
													OR ABS(a.AmountOnHand) >= .05)''
end 
end -- item summarization
end -- p/e

---------------------------------------------------------------------------------------------------------------------------------------------------------
if ( @debug = 1 ) print @sql
exec sp_executeSQL @sql

set nocount off

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetRPerpetualInv] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetRPerpetualInvExp]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetRPerpetualInvExp]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

CREATE PROCEDURE [dbo].[usp2GetRPerpetualInvExp]
       @companyNumber varchar(5) = ''''
			,@accountnumber varchar(28) = ''''
			,@businessunit varchar(12) = ''''
			,@periodends smalldatetime = null
			,@excludeCompanies varchar(255) = null
			,@AOHThreshold int = null
			,@CommonUOM char(2) = null
			,@SummarizeByItem char(1) = ''N''
			,@debug bit = 0
			
AS 
/*
04/10/2007	raw	creation
04/11/2007	raw	added missing UOM conversion check to as of branch
02/01/2008	raw	optimize and add UOM conversion
02/14/2008	raw	add item summarization
03/06/2008	raw	added AOH lookup

-----------------------------------------------
-- regular, no summarize
exec usp2getrperpetualinv
--@companynumber = ''01160''
--@accountnumber = ''11601000.1355  .000     ''
@businessunit = ''    11601000''
--,@excludecompanies = ''01002''
,@AOHThreshold = -9999
,@debug = 1

-----------------------------------------------
-- regular, no summarize, commonuom
exec usp2getrperpetualinv
--@companynumber = ''01160''
@accountnumber = ''11601000.1355  .000     ''
--@businessunit = ''    11601000''
--,@excludecompanies = ''01002''
--@AOHThreshold = -99
,@CommonUOM = ''EA''
,@debug = 1

-----------------------------------------------
-- regular, summarize
exec usp2getrperpetualinv
--@companynumber = ''01160''
@accountnumber = ''11601000.1355  .000     ''
--@businessunit = ''    11601000''
--,@excludecompanies = ''01002''
--@AOHThreshold = -99
,@SummarizeByItem = ''Y''
,@debug = 1

-----------------------------------------------
-- regular, summarize, commonUOM
exec usp2getrperpetualinv
--@companynumber = ''01160''
@accountnumber = ''11601000.1355  .000     ''
--@businessunit = ''    11601000''
--,@excludecompanies = ''01002''
--@AOHThreshold = -99
,@CommonUOM = ''EA''
,@SummarizeByItem = ''Y''
,@debug = 1

-----------------------------------------------
-- p/e, no summarize
exec usp2getrperpetualinv
--@companynumber = ''01160''
--@accountnumber = ''11601000.1355  .000     ''
--@businessunit = ''    11601000''
@periodends = ''3/31/07''
--,@excludecompanies = ''01002''
--@AOHThreshold = -99
,@debug = 1

-----------------------------------------------
-- p/e, no summarize, commonUOM
exec usp2getrperpetualinv
--@companynumber = ''01160''
@accountnumber = ''11601000.1355  .000     ''
--@businessunit = ''    11601000''
,@periodends = ''3/31/07''
--,@excludecompanies = ''01002''
--@AOHThreshold = -99
--,@CommonUOM = ''EA''
,@debug = 1

-----------------------------------------------
-- p/e, summarize
exec usp2getrperpetualinv
--@companynumber = ''01160''
@accountnumber = ''11601000.1355  .000     ''
--@businessunit = ''    11601000''
,@periodends = ''3/31/07''
--,@excludecompanies = ''01002''
--@AOHThreshold = -99
,@SummarizeByItem = ''Y''
,@debug = 1

-----------------------------------------------
-- p/e, summarize, commonUOM
exec usp2getrperpetualinv
--@companynumber = ''01160''
@accountnumber = ''11101000.1353  .000     ''
--@accountnumber = ''11601000.1355  .000     ''
--@businessunit = ''    11601000''
,@periodends = ''3/31/07''
--,@excludecompanies = ''01002''
--@AOHThreshold = -99
,@CommonUOM = ''EA''
,@SummarizeByItem = ''Y''
,@debug = 1

----------------------------------------------------
exec usp2getrperpetualinv
--@companynumber = ''01110''
--@accountnumber = ''11601000.1355  .000     ''
@businessunit = ''    11601000''
,@periodends = ''3/31/07''
--,@excludecompanies = ''01002''
,@AOHThreshold = -9999
,@CommonUOM = ''''
,@SummarizeByItem = ''Y''
,@debug = 1


*/
	set nocount on

	declare @sql nvarchar(4000)
	declare @where nvarchar(2000)
	declare @orderby nvarchar(2000)

	set @sql = ''''
	set @where = ''''
	set @orderby = ''''

	-- lookup aoh if requested
	if ( @AOHThreshold = -9999 ) begin
		set @AOHThreshold = ( SELECT  Threshold1 FROM    RConstants)
	end

	if ( @CommonUOM = '''' ) begin
		set @CommonUOM = null
	end
---------------------------------------------------------------------------------------------------------------------------------------------------------
-- set up conversion factor table
    
if ( @CommonUOM is not null ) begin
	set @sql = @sql + ''TRUNCATE TABLE EXPConversions
	
	''
	
	if ( @periodends is null ) begin
		set @sql = @sql + ''
			insert EXPConversions(ConverterBranchPlant,ConverterShortItem,ConverterUOM,ConverterCommonUOM)
			select distinct branchplant,shortitem,UnitOfMeasure As UOM,'''''' + @CommonUOM + ''''''
				FROM    dbo.RPerpetualInv rpi
				INNER JOIN RCompanies c On (rpi.CompanyNumber = c.CompanyNumber) 
				inner join dbo.RInvAccountList al on rpi.longaccount = al.longaccount ''

		exec usp2GetStandardFilters
			@companynumber=@companyNumber
		, @companynumberalias = ''rpi''
		, @accountnumber = @accountNumber
		, @accountnumberalias = ''rpi''
		, @accountnumbercolname = ''longaccount''
		, @businessunit = @businessUnit
		, @businessunitalias = ''al''
		, @periodends = @periodends
		, @periodendsalias = ''''
		, @excludecompanies = @excludeCompanies
		, @filterClause = @where output

	end
	else begin
		set @sql = @sql + ''
			insert EXPConversions(ConverterBranchPlant,ConverterShortItem,ConverterUOM,ConverterCommonUOM)
			select distinct iao.branchplant,iao.shortitem,UnitOfMeasure As UOM,'''''' + @CommonUOM + ''''''
				FROM    dbo.RInvAsOf iao
				INNER JOIN RCompanies c On (iao.CompanyNumber = c.CompanyNumber)
				left join dbo.rperpetualinv rpi
							on iao.companynumber = rpi.companynumber
							and iao.longaccount = rpi.longaccount
							and iao.branchplant = rpi.branchplant
							and iao.shortitem = rpi.shortitem
							and iao.itemnumber = rpi.itemnumber
							and iao.location = rpi.location
							and iao.lot = rpi.lot 
				inner join dbo.RInvAccountList al on iao.longaccount = al.longaccount ''


		exec usp2GetStandardFilters
			@companynumber=@companyNumber
		, @companynumberalias = ''iao''
		, @accountnumber = @accountNumber
		, @accountnumberalias = ''iao''
		, @accountnumbercolname = ''longaccount''
		, @businessunit = @businessUnit
		, @businessunitalias = ''al''
		, @periodends = @periodends
		, @periodendsalias = ''iao''
		, @excludecompanies = @excludeCompanies
		, @filterClause = @where output
	end
	
	if ( len(@where) > 0 ) begin
		set @sql = @sql + ''
			WHERE '' + @where
	end

	-- update conv factor
	set @sql = @sql + ''
			update EXPConversions
				set ConversionFactor = dbo.Convert_Primary_UOM(ConverterBranchPlant,ConverterShortItem,ConverterUOM,ConverterCommonUOM)''

	set @sql = @sql + ''

	''

end
---------------------------------------------------------------------------------------------------------------------------------------------------------
	if ( @periodends is null ) begin
/* NOTE col order is expected as follows
	Branch:			3
	ItemNumber:	4
	Location:		5
	Lot:				6
*/

		if ( @SummarizeByItem = ''N'' ) begin
			set @sql = @sql + ''SELECT  LTRIM(RTRIM(rpi.CompanyNumber)) AS Company,
							rpi.LongAccount,
							LTRIM(BranchPlant) AS Branch,
							ShortItem,
							ItemNumber,
							ItemDescription,
							AmountonHand,
							Location,
							Lot,
							GLClass,
							--SalesCategory01Code ,
							--SalesCategory02Code ,
							--SalesCategory03Code ,
							--SalesCategory04Code ,
							--SalesCategory05Code ,
							--SalesCategory06Code ,
							--SalesCategory07Code ,
							--SalesCategory08Code ,
							--SalesCategory09Code ,
							--SalesCategory10Code ,
							--PurchasingCategory01Code ,
							--PurchasingCategory02Code ,
							--PurchasingCategory03Code ,
							--PurchasingCategory04Code ,
							--PurchasingCategory05Code ,
							--PurchasingCategory06Code ,
							--PurchasingCategory07Code ,
							--PurchasingCategory08Code ,
							--PurchasingCategory09Code ,
							--PurchasingCategory10Code ,
							UnitofMeasure AS UOM,
							rpi.QuantityonHand AS QOH,
							UnitCost as Cost,''
							if ( @CommonUOM is not null ) begin
								set @sql = @sql + ''
										'''''' + @commonuom + '''''' as ComUOM,
											case when conversionfactor = 0 then 0 else cast((rpi.QuantityonHand / converter.ConversionFactor) as DECIMAL(18, 2)) end as ComQOH,
										cast((UnitCost * converter.ConversionFactor) as decimal(18,6)) as ComCost,
										ConversionFactor,''
							end
			set @sql = @sql + ''
							StockingType AS ST,
							CostMethod AS CM,
							Material,
							Labor,
							Overhead,
							CASE WHEN CostMethod = ''''07'''' AND
												ABS(UnitCost - CONVERT(DECIMAL(18, 2), ( Material + Labor + Overhead ))) > .01 THEN ''''*''''
									 ELSE ''''''''
							END AS CI,
							BaselineVar AS AmountVar,
							EstUnits AS QuantityVar,
							al.BusinessUnit AS BusinessUnit,
							al.ObjectAccount''
			
			-- from
			set @sql = @sql + ''
			FROM    dbo.RPerpetualInv rpi
			INNER JOIN RCompanies c On (rpi.CompanyNumber = c.CompanyNumber) 
			INNER JOIN dbo.rinvaccountlist al
							ON rpi.longaccount = al.longaccount AND
								 al.companynumber = rpi.companynumber''

			if ( @CommonUOM is not null ) begin
				set @sql = @sql + ''
				left join (select * from EXPConversions) converter
										on converter.ConverterBranchPlant = rpi.branchplant
										and converter.ConverterShortItem = rpi.shortitem
										and converter.ConverterUOM = rpi.UnitofMeasure
										and converter.ConverterCommonUOM = '''''' + @CommonUOM + ''''''''
			end		
		
			-- where
			set @sql = @sql + '' 
				WHERE ( rpi.QuantityonHand <> 0 OR BaselineVar <> 0 )''
			if ( @AOHThreshold is not null ) begin
				set @sql = @sql + ''
					AND ( rpi.QuantityonHand != 0 OR ABS(AmountOnHand) >= '' + cast(@AOHThreshold as varchar) + '')''
			end
			
			if ( len(@where) = 0 ) begin
				exec usp2GetStandardFilters
					@companynumber=@companyNumber
				, @companynumberalias = ''rpi''
				, @accountnumber = @accountNumber
				, @accountnumberalias = ''rpi''
				, @accountnumbercolname = ''longaccount''
				, @businessunit = @businessUnit
				, @businessunitalias = ''al''
				, @periodends = @periodends
				, @periodendsalias = ''''
				, @excludecompanies = @excludeCompanies
				, @filterClause = @where output
			end
	
			if ( len(@where) > 0 ) begin
				set @sql = @sql + ''
					AND '' + @where
			end
			
			-- order by
			set @sql = @sql + ''			
				Order By	rpi.CompanyNumber, BranchPlant, ItemNumber, Location, Lot''

		end
---------------------------------------------------------------------------------------------------------------------------------------------------------
		else begin -- summarizebyitem == ''Y''
			set @sql = @sql + ''SELECT * FROM (SELECT  LTRIM(RTRIM(rpi.CompanyNumber)) AS Company,
							rpi.LongAccount,
							LTRIM(BranchPlant) AS Branch,
							ShortItem,
							ItemNumber,
							ItemDescription,
							Sum(AmountonHand) as AmountOnHand,
							UnitofMeasure AS UOM,
							Sum(rpi.QuantityonHand) AS QOH,
							MAX(UnitCost) as Cost,''

							if ( @CommonUOM is not null ) begin
								set @sql = @sql + ''
											'''''' + @commonuom + '''''' as ComUOM,
											case when conversionfactor = 0 then 0 else cast((Sum(rpi.QuantityonHand) / ConversionFactor) as DECIMAL(18, 2)) end as ComQOH,
										cast((Max(UnitCost) * converter.ConversionFactor) as decimal(18,6)) as ComCost,
										ConversionFactor,''
							end

			set @sql = @sql + ''
							Sum(BaselineVar) AS AmountVar,
							Sum(EstUnits) AS QuantityVar,
							al.BusinessUnit AS BusinessUnit,
							al.ObjectAccount''
		

			-- from
			set @sql = @sql + ''
			FROM    dbo.RPerpetualInv rpi
			INNER JOIN RCompanies c On (rpi.CompanyNumber = c.CompanyNumber) 
			INNER JOIN dbo.rinvaccountlist al
							ON rpi.longaccount = al.longaccount AND
								 al.companynumber = rpi.companynumber''

			if ( @CommonUOM is not null ) begin
				set @sql = @sql + ''
				left join (select * from EXPConversions) converter
										on converter.ConverterBranchPlant = rpi.branchplant
										and converter.ConverterShortItem = rpi.shortitem
										and converter.ConverterUOM = rpi.UnitofMeasure
										and converter.ConverterCommonUOM = '''''' + @CommonUOM + ''''''''
			end		
			
			-- inner where			
			if ( len(@where) = 0 ) begin
				exec usp2GetStandardFilters
					@companynumber=@companyNumber
				, @companynumberalias = ''rpi''
				, @accountnumber = @accountNumber
				, @accountnumberalias = ''rpi''
				, @accountnumbercolname = ''longaccount''
				, @businessunit = @businessUnit
				, @businessunitalias = ''al''
				, @periodends = @periodends
				, @periodendsalias = ''''
				, @excludecompanies = @excludeCompanies
				, @filterClause = @where output
			end
	
			if ( len(@where) > 0 ) begin
				set @sql = @sql + ''
					WHERE '' + @where
			end
			
			-- group by
			set @sql = @sql + ''
				group by rpi.CompanyNumber,rpi.LongAccount,BranchPLant,ItemNumber,ItemDescription,UnitofMeasure,BusinessUnit,ObjectAccount,ShortItem''
			if ( @CommonUOM is not null ) begin
				set @sql = @sql + '',ConversionFactor''
			end

			-- finish inner query
			set @sql = @sql + '') a''

			-- outer where
			set @sql = @sql + '' 
				WHERE ( QOH <> 0 OR AmountVar <> 0 )''
			if ( @AOHThreshold is not null ) begin
				set @sql = @sql + ''
					AND ( QOH != 0 OR ABS(AmountOnHand) >= '' + cast(@AOHThreshold as varchar) + '')''
			end

			-- order by
			set @sql = @sql + ''			
				Order By	Company, Branch, ItemNumber''
		
		end -- item summ
	end -- p/e
---------------------------------------------------------------------------------------------------------------------------------------------------------
	else begin -- p/e branch
		/* NOTE col order is expected as follows
			Branch:			4
			ItemNumber:	5
			Location:		7
			Lot:				8
			QOH:			 10
			HasMissing:15 
		*/
		if ( @SummarizeByItem = ''N'' ) begin
			set @sql = @sql + ''SELECT  iao.CompanyNumber AS Company,
						iao.PeriodEnds,
						iao.LongAccount,
						LTRIM(iao.BranchPlant) AS Branch,
						iao.ShortItem,
						iao.ItemNumber,
						ItemDescription,
						iao.Location,
						iao.Lot,
						iao.GLClass,
						--SalesCategory01Code ,
						--SalesCategory02Code ,
						--SalesCategory03Code ,
						--SalesCategory04Code ,
						--SalesCategory05Code ,
						--SalesCategory06Code ,
						--SalesCategory07Code ,
						--SalesCategory08Code ,
						--SalesCategory09Code ,
						--SalesCategory10Code ,
						--PurchasingCategory01Code ,
						--PurchasingCategory02Code ,
						--PurchasingCategory03Code ,
						--PurchasingCategory04Code ,
						--PurchasingCategory05Code ,
						--PurchasingCategory06Code ,
						--PurchasingCategory07Code ,
						--PurchasingCategory08Code ,
						--PurchasingCategory09Code ,
						--PurchasingCategory10Code ,
						UnitofMeasure as UOM,
						case when uom.ItemNumber IS NULL
							then CONVERT(DECIMAL(18, 2), iao.QuantityonHand)
							else -9999
						end as QOH,
						--isnull(rpi.UnitCost, 0) as CurrCost,''

						if ( @CommonUOM is not null ) begin
							set @sql = @sql + ''
										'''''' + @commonuom + '''''' as ComUOM,
										case when uom.ItemNumber IS NULL
											then case when converter.ConversionFactor = 0 then 0 else CONVERT(DECIMAL(18, 2), (iao.QuantityOnHand / converter.ConversionFactor) ) end
											else -9999
										end as ComQOH,
										cast(isnull(rpi.UnitCost,0) * converter.ConversionFactor as decimal(18,6)) as ComCost,
									converter.ConversionFactor,''
						end

			set @sql = @sql + ''
						iao.AmountonHand,
						al.BusinessUnit AS BusinessUnit,
						al.ObjectAccount,
						case when uom.ItemNumber IS NULL then ''''N'''' else ''''Y'''' end as HasMissingConversion''

			-- from
			set @sql = @sql + ''
					FROM  dbo.RInvAsOf iao
					INNER JOIN RCompanies c On (iao.CompanyNumber = c.CompanyNumber) 
					INNER JOIN dbo.rinvaccountlist al
									ON iao.longaccount = al.longaccount
					left join dbo.rperpetualinv rpi
							on iao.companynumber = rpi.companynumber
							and iao.longaccount = rpi.longaccount
							and iao.branchplant = rpi.branchplant
							and iao.shortitem = rpi.shortitem
							and iao.itemnumber = rpi.itemnumber
							and iao.location = rpi.location
							and iao.lot = rpi.lot
					LEFT JOIN dbo.v_Integrity4_UOM_Conv uom
									ON iao.ItemNumber = uom.ItemNumber''
			if ( @CommonUOM is not null ) begin
				set @sql = @sql + ''
				left join (select * from EXPConversions) converter
										on converter.ConverterBranchPlant = iao.branchplant
										and converter.ConverterShortItem = iao.shortitem
										and converter.ConverterUOM = rpi.UnitofMeasure
										and converter.ConverterCommonUOM = '''''' + @CommonUOM + ''''''''
			end	

			-- where
			set @sql = @sql + '' 
			WHERE ( iao.QuantityonHand <> 0 OR ABS(CONVERT(DECIMAL(18, 2), iao.AmountonHand)) >= .01 )''
			if ( @AOHThreshold is not null ) begin
				set @sql = @sql + ''
						AND ( case when uom.ItemNumber IS NULL then CONVERT(DECIMAL(18, 2), iao.QuantityonHand) else -9999 end != 0 
							OR ABS(iao.AmountOnHand) >= '' + cast(@AOHThreshold as varchar) + '')''
			end 

			if ( len(@where) = 0 ) begin
				exec usp2GetStandardFilters
					@companynumber=@companyNumber
				, @companynumberalias = ''iao''
				, @accountnumber = @accountNumber
				, @accountnumberalias = ''iao''
				, @accountnumbercolname = ''longaccount''
				, @businessunit = @businessUnit
				, @businessunitalias = ''al''
				, @periodends = @periodends
				, @periodendsalias = ''iao''
				, @excludecompanies = @excludeCompanies
				, @filterClause = @where output
			end

			if ( len(@where) > 0 ) begin
				set @sql = @sql + ''
					AND '' + @where
			end

			-- order by
			set @sql = @sql + ''
				ORDER BY iao.CompanyNumber,
								iao.PeriodEnds,
								iao.LongAccount,
								iao.BranchPlant,
								iao.ItemNumber,
								iao.Location,
								iao.Lot''

		end
---------------------------------------------------------------------------------------------------------------------------------------------------------
		else begin -- summarize by item
			set @sql = @sql + ''SELECT  a.Company,
						a.PeriodEnds,
						LongAccount,
						LTRIM(a.Branch) as Branch,
						a.ShortItem,
						a.ItemNumber,
						ItemDescription,
						UOM,
						case when uom.ItemNumber IS NULL
							then CONVERT(DECIMAL(18, 2), a.QuantityonHand)
							else -9999
						end as QOH,
						unitcost as CurrCost,''

						if ( @CommonUOM is not null ) begin
							set @sql = @sql + ''
										'''''' + @commonuom + '''''' as ComUOM,
										case when uom.ItemNumber IS NULL
											then case when converter.ConversionFactor = 0 then 0 else CONVERT(DECIMAL(18, 2), (a.QuantityOnHand / converter.ConversionFactor) ) end
											else -9999
										end as ComQOH,
										cast(a.UnitCost * converter.ConversionFactor as decimal(18,6)) as ComCost,
										converter.ConversionFactor,''
						end

			set @sql = @sql + ''
						AmountonHand,
						BusinessUnit,
						ObjectAccount,
						case when uom.ItemNumber IS NULL then ''''N'''' else ''''Y'''' end as HasMissingConversion''

			set @sql = @sql + ''
					FROM  (SELECT  iao.CompanyNumber AS Company,
								iao.PeriodEnds,
								iao.LongAccount,
								iao.BranchPlant AS Branch,
								iao.ItemNumber,
								iao.ShortItem,
								ItemDescription,
								sum(iao.QuantityOnHand) as QuantityonHand,
								UnitofMeasure AS UOM,
								sum(iao.AmountonHand) as AmountOnHand,
								al.BusinessUnit AS BusinessUnit,
								al.ObjectAccount,
								max(isnull(rpi.unitcost,0)) as UnitCost
						FROM    dbo.RInvAsOf iao
						INNER JOIN RCompanies c On (iao.CompanyNumber = c.CompanyNumber) 
						INNER JOIN dbo.rinvaccountlist al
										ON iao.longaccount = al.longaccount
						left join dbo.rperpetualinv rpi
							on iao.companynumber = rpi.companynumber
							and iao.longaccount = rpi.longaccount
							and iao.branchplant = rpi.branchplant
							and iao.shortitem = rpi.shortitem
							and iao.itemnumber = rpi.itemnumber
							and iao.location = rpi.location
							and iao.lot = rpi.lot''

			-- inner where
			if ( len(@where) = 0 ) begin
				exec usp2GetStandardFilters
					@companynumber=@companyNumber
				, @companynumberalias = ''iao''
				, @accountnumber = @accountNumber
				, @accountnumberalias = ''iao''
				, @accountnumbercolname = ''longaccount''
				, @businessunit = @businessUnit
				, @businessunitalias = ''al''
				, @periodends = @periodends
				, @periodendsalias = ''iao''
				, @excludecompanies = @excludeCompanies
				, @filterClause = @where output
			end

			if ( len(@where) > 0 ) begin
				set @sql = @sql + ''
					WHERE '' + @where
			end

			-- group by for item summarization
			set @sql = @sql + ''
					group by iao.CompanyNumber,iao.PeriodEnds,iao.LongAccount,iao.BranchPlant,iao.ItemNumber,ItemDescription,UnitofMeasure,BusinessUnit,ObjectAccount,iao.ShortItem''

			-- finish subquery, outer joins
			set @sql = @sql + '')a
							LEFT JOIN dbo.v_Integrity4_UOM_Conv uom
								ON a.ItemNumber = uom.ItemNumber ''

			if ( @CommonUOM is not null ) begin
				set @sql = @sql + ''
				left join (select * from EXPConversions) converter
										on converter.ConverterBranchPlant = a.branch
										and converter.ConverterShortItem = a.shortitem
										and converter.ConverterUOM = a.UOM
										and converter.ConverterCommonUOM = '''''' + @CommonUOM + ''''''''
			end

			-- outer where where
			set @sql = @sql + '' 
			WHERE ( a.QuantityonHand <> 0 OR ABS(CONVERT(DECIMAL(18, 2), a.AmountonHand)) >= .01 )''
			if ( @AOHThreshold is not null ) begin
				set @sql = @sql + ''
						AND ( case when uom.ItemNumber IS NULL then CONVERT(DECIMAL(18, 2), a.QuantityonHand) else -9999 end != 0 
							OR ABS(a.AmountOnHand) >= '' + cast(@AOHThreshold as varchar) + '')''
			end 

			-- order by
			set @sql = @sql + ''
				ORDER BY a.Company,
								a.PeriodEnds,
								a.LongAccount,
								a.Branch,
								a.ItemNumber''



		end -- item summarization


	end -- p/e
---------------------------------------------------------------------------------------------------------------------------------------------------------

	if ( @debug = 1 ) print @sql
	exec sp_executeSQL @sql

set nocount off


' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetRPerpetualInvExp] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetRUnpostedBatches]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetRUnpostedBatches]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/****** Object:  StoredProcedure [dbo].[usp2GetRUnpostedBatches]    Script Date: 03/18/2011 05:49:06 ******/
-----------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[usp2GetRUnpostedBatches] 
 @companyNumber varchar(5) = ''''
,@accountnumber varchar(28) = ''''
,@businessunit varchar(12) = ''''
,@periodends smalldatetime = null
,@excludeCompanies varchar(255) = null
,@debug bit = 0
As
set nocount on

	declare @sql nvarchar(4000)
	declare @where varchar(1024)

	-- select
	set @sql = ''Select ltrim(rup.CompanyNumber) as Company,
						Case When ICDICJ IS NULL Then ''''1901-01-01'''' Else ICDICJ End As BatchDate,
						PeriodEnds,
						UserName as [User],
						rup.LongAccount as Account,
						BatchNumber,
						BatchType as Type,
						OpenAmount,
						App As Approval_Status,
						Post As Posting_Status,
						ltrim(al.BusinessUnit) as BusinessUnit,
						al.ObjectAccount
	FROM    	RUnpostedBatches rup
		Inner join RCompanies c on rup.companynumber = c.companynumber
		inner join rinvaccountlist al on rup.longaccount = al.longaccount and rup.companynumber = al.companynumber
		left outer join vcr_F0011 On Batchnumber = ICICU and BatchType = ICICUT
	WHERE  	  OpenAmount <> 0 ''
	
		
	-- where
	exec usp2GetStandardFilters
		@companynumber=@companyNumber
	, @companynumberalias = ''al''
	, @accountnumber = @accountNumber
	, @accountnumberalias = ''al''
	, @accountnumbercolname = ''longaccount''
	, @businessunit = @businessUnit
	, @businessunitalias = ''al''
	, @periodends = @periodends
	, @periodendsalias = ''rup''
	, @excludecompanies = @excludeCompanies
	, @filterClause = @where output
	
	if ( len(@where) > 0 ) begin
		set @sql = @sql + '' 
		AND '' + @where
	end
	
	-- order by
  set @sql = @sql +  '' 
		ORDER BY  rup.CompanyNumber, PeriodEnds, Username, rup.LongAccount, BatchNumber''

	if ( @debug = 1 ) print ''['' + @sql + '']''
	exec sp_executeSQL @sql

set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetRUnpostedBatches] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetRUnpostedBatchesByAccount]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetRUnpostedBatchesByAccount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2GetRUnpostedBatchesByAccount] 
 @companyNumber varchar(5) = ''''
,@accountnumber varchar(28) = ''''
,@businessunit varchar(12) = ''''
,@periodends smalldatetime = null
,@excludeCompanies varchar(255) = null
As
/*
	exec [dbo].[usp2GetRUnpostedBatchesByAccount] 
	 --@companynumber=''10220''
	--@accountnumber=''102910002.116110''
	@businessunit = ''102910002''
	,@periodends=''11/30/2006''


select * from rinvaccountlist
*/

set nocount on

	declare @pe varchar(30)

	if ( @companynumber = '''' ) begin
		set @companynumber = ''%''
	end
	if ( @accountnumber = '''' ) begin
		set @accountnumber = ''%''
	end
	if ( @businessunit = '''' ) begin
		set @businessunit = ''%''
	end
	if ( @periodends is null ) begin
		set @pe = ''%''
	end
	else begin
		set @pe = convert(varchar(30),@periodends,112)
	end
	 
	Select		ltrim(rup.CompanyNumber) as ''Company'',
						PeriodEnds,
						UserName as ''User'',
						rup.LongAccount as ''Account'',
						BatchNumber,
						BatchType as ''Type'',
						OpenAmount,
						App As Approval_Status,
						Post As Posting_Status,
						ltrim(al.BusinessUnit) as ''BusinessUnit'',
						al.ObjectAccount
	INTO			#temp
	FROM    	RUnpostedBatches rup
		Inner join RCompanies c on rup.companynumber = c.companynumber
		inner join rinvaccountlist al on rup.longaccount = al.longaccount and rup.companynumber = al.companynumber
	WHERE  	  OpenAmount <> 0 
						And rup.CompanyNumber like @companyNumber 
						and rup.LongAccount like @AccountNumber
						and al.businessunit like @businessunit
						and convert(varchar(30),rup.PeriodEnds,112) like @pe
	ORDER BY  rup.CompanyNumber, PeriodEnds, Username, rup.LongAccount, BatchNumber

	if ( @excludeCompanies is not null ) begin
		select * from #temp where company not in (select * from dbo.fn_SplitString(@excludeCompanies,'',''))
	end
	else begin
		select * from #temp 
	end

	drop table #temp

set nocount off

/****** Object:  StoredProcedure [dbo].[usp2GetRUnpostedCardex]    Script Date: 10/31/2007 16:59:33 ******/
SET ANSI_NULLS ON
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetRUnpostedBatchesByAccount] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetRUnpostedCardex]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetRUnpostedCardex]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-----------------------------------------------------------------------------------------
CREATE     PROCEDURE [dbo].[usp2GetRUnpostedCardex] 
 @companyNumber varchar(5) = ''''
,@accountnumber varchar(28) = ''''
,@businessunit varchar(12) = ''''
,@periodends smalldatetime = null
,@excludeCompanies varchar(255) = null
,@debug bit = 0
As
/*


exec [dbo].usp2GetRUnpostedCardex 
 @companyNumber = ''01002''
,@accountnumber = ''10021000.1353  .001     ''
,@businessunit = ''''
,@periodends = ''4/30/2007''
,@excludeCompanies = null
,@debug = 1
	
select * from rinvaccountlist
*/
set nocount on

	declare @sql nvarchar(4000)
	declare @where varchar(1024)




	-- select
	set @sql = ''	SELECT 
					ltrim(rtrim(UCX.CompanyNumber)) as Company,
					TransactionDate,
					PeriodEnds,
					UCX.LongAccount as Account,
					OrderType,
					DocType,
					DocNumber,
					TransactionAmount,
					Status,
					BranchPlant,
					ltrim(al.BusinessUnit) as BusinessUnit,
					al.ObjectAccount
	FROM    RUnpostedCardex UCX
		Inner Join	RCompanies COMP On (COMP.CompanyNumber = UCX.CompanyNumber)
		inner join rinvaccountlist al on UCX.longaccount = al.longaccount
	WHERE transactionamount <> 0 And al.LongAccount Not In (''''GL Class Not In Base Table'''',''''Outside Operations'''')''
	


	-- where
	exec usp2GetStandardFilters
		@companynumber=@companyNumber
	, @companynumberalias = ''al''
	, @accountnumber = @accountNumber
	, @accountnumberalias = ''al''
	, @accountnumbercolname = ''longaccount''
	, @businessunit = @businessUnit
	, @businessunitalias = ''al''
	, @periodends = @periodends
	, @periodendsalias = ''UCX''
	, @excludecompanies = @excludeCompanies
	, @filterClause = @where output
	
	if ( len(@where) > 0 ) begin
		set @sql = @sql + '' 
		AND '' + @where
	end
	
	-- order by
  set @sql = @sql +  '' 
		ORDER BY UCX.CompanyNumber, TransactionDate, UCX.LongAccount, DocType, DocNumber''

	if ( @debug = 1 ) print ''['' + @sql + '']''
	exec sp_executeSQL @sql


	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetRUnpostedCardex] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetRUnpostedCardexByAccount]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetRUnpostedCardexByAccount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE     PROCEDURE [dbo].[usp2GetRUnpostedCardexByAccount] 
 @companyNumber varchar(5) = ''''
,@accountnumber varchar(28) = ''''
,@businessunit varchar(12) = ''''
,@periodends smalldatetime = null
,@excludeCompanies varchar(255) = null
As
/*
	exec [dbo].[usp2GetRUnpostedCardexByAccount] 
	 @excludeCompanies = ''01002''
	
select * from rinvaccountlist
*/
set nocount on

	declare @pe varchar(30)

	if ( @companynumber = '''' ) begin
		set @companynumber = ''%''
	end
	if ( @accountnumber = '''' ) begin
		set @accountnumber = ''%''
	end
	if ( @businessunit = '''' ) begin
		set @businessunit = ''%''
	end
	if ( @periodends is null ) begin
		set @pe = ''%''
	end
	else begin
		set @pe = convert(varchar(30),@periodends,112)
	end

	SELECT 
					ltrim(rtrim(UCX.CompanyNumber)) as ''Company'',
					TransactionDate,
					PeriodEnds,
					UCX.LongAccount as ''Account'',
					OrderType,
					DocType,
					DocNumber,
					TransactionAmount,
					Status,
					BranchPlant,
					ltrim(al.BusinessUnit) as ''BusinessUnit'',
					al.ObjectAccount
	INTO	  #temp
	FROM    RUnpostedCardex UCX
		Inner Join	RCompanies COMP On (COMP.CompanyNumber = UCX.CompanyNumber)
		inner join rinvaccountlist al on UCX.longaccount = al.longaccount
	WHERE
		UCX.CompanyNumber like @companyNumber 
		and  UCX.LongAccount like @accountNumber 
		and al.businessunit like @businessunit
		and convert(varchar(30),UCX.PeriodEnds,112) like @pe
		and transactionamount <> 0 
	ORDER BY UCX.CompanyNumber, TransactionDate, UCX.LongAccount, DocType, DocNumber


	if ( @excludeCompanies is not null ) begin
		select * from #temp where company not in (select * from dbo.fn_SplitString(@excludeCompanies,'',''))
	end
	else begin
		select * from #temp 
	end

	drop table #temp

set nocount off

/****** Object:  StoredProcedure [dbo].[usp2GetRVarianceSummary]    Script Date: 10/31/2007 17:00:20 ******/
SET ANSI_NULLS ON
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetRUnpostedCardexByAccount] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetRViewNames]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetRViewNames]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

create PROCEDURE [dbo].[usp2GetRViewNames]
    ( @report_type VARCHAR(50) )
AS 
/*
exec usp2getrviewnames ''custom''
select * from rviewnames
*/
	SET nocount ON

	SELECT  name,name_of_view,view_description,crystalreportname
		,name + ''    ( '' + isnull(view_description,'''') + '' )'' as DisplayDescr
	FROM    RViewNames
	WHERE   report_type = @report_type AND
					active = 1
	ORDER BY Sort

	SET nocount OFF
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetRViewNames] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetServerStatus]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetServerStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/**********************************************************
 Update server status to filter admin logs out
***********************************************************/
CREATE PROCEDURE [dbo].[usp2GetServerStatus] (
	 @LightStatus char(1) = '''' output
	,@Process varchar(100) = '''' output
	,@Error varchar(100) = '''' output
	,@AsOf smalldatetime = null output
)
AS
/*

	declare @l char(1)
	declare @p varchar(100)
	declare @e varchar(100)
	declare @a smalldatetime
	exec usp2GetServerStatus @l output,@p output, @e output, @a output
	
	select @l,@p,@e,@a

	select  top 10 *
	from rserver_log
	order by time1 desc

*/

	set nocount on
	
	declare @isRunning int

	-- display data
	select top 1 @Process= Step, @Error= Process
	from rserver_log 
	where step not in ( ''Company'', ''Constants'', ''Users'' )
	order by time1 desc

	select @AsOf = cast(substring(oobrollok,7,50) as smalldatetime)
	from rinvaccountsummary
	where glrollok like ''End%''
		and periodbegins != ''1/1/1900''

	set @Process = IsNull(@Process,'''')
	set @Error = IsNull(@Error,'''')

--	-- job status
--	-- is job running now?
--	exec @isRunning = dbo.usp2RefreshRunning
--	if ( @isRunning = 1 ) begin
--			set @LightStatus = ''Y''
--			set @Error = ''Running...''
--			return
--	end

	if ( @Error = ''Successfully Completed'' ) begin
		set @LightStatus = ''G''
	end
	else begin
		set @LightStatus = ''R''
	end


	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetServerStatus] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetSPLevel]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetSPLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2GetSPLevel] 
	@Level varchar(25) = '''' output
AS
BEGIN
	SET NOCOUNT ON;

	set @Level = (select top 1 value from dbo.RSystemVariables where [name] = ''DatabaseVersion'')
END
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetSPLevel] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetStandardFilters]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetStandardFilters]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2GetStandardFilters] 
	-- Add the parameters for the stored procedure here
	 @companyNumber varchar(5) = ''''
	,@companyNumberAlias varchar(24)
	,@companyNumberColName varchar(50) = ''companynumber''
	,@accountnumber varchar(28) = ''''
	,@accountNumberAlias varchar(24)
	,@accountNumberColName varchar(50) = ''accountnumber''
	,@businessunit varchar(12) = ''''
	,@businessUnitAlias varchar(24)
	,@periodends smalldatetime = null
	,@periodEndsAlias varchar(24)
	,@usePeriodEndsLE bit = 0
	,@excludeCompanies varchar(255) = null
	,@filterClause varchar(1024) = '''' output
	,@debug bit = 0
AS

/*

declare @filterclause varchar(1024)

exec usp2GetStandardFilters
 @companynumber = ''''
,@companynumberalias = ''clc''
--,@companynumbercolname = null
,@accountnumber = ''1111''
,@accountnumberalias = ''accttable''
--,@accountnumbercolname = null
--,@businessunit = null
,@businessunitalias = ''butable''
,@periodends = ''1/31/2008''
,@periodendsalias = ''petable''
,@useperiodendsle = 0
,@excludecompanies = ''0160,0130,''
,@filterclause = @filterclause output
,@debug = 1

select @filterclause

*/
BEGIN

	SET NOCOUNT ON
	declare @peOp varchar(2)
	set @peOp = ''=''
	set @filterClause = ''''

	if ( substring(@excludeCompanies,len(@excludeCompanies),1) = '','' ) begin
		set @excludeCompanies = substring(@excludeCompanies,0,len(@excludeCompanies))
	end

  if ( @companynumber is not null and @companynumber != '''' ) begin
		if ( len(@filterclause) != 0 ) begin
			set @filterclause = @filterclause + '' and ''
		end
		set @filterClause = @filterClause + @companyNumberAlias + ''.'' + @companyNumberColName + '' = '''''' + @companyNumber + ''''''''
	end

	if ( @accountnumber is not null and @accountnumber != '''' ) begin
		if ( len(@filterclause) != 0 ) begin
			set @filterclause = @filterclause + '' and ''
		end
		set @filterClause = @filterClause + @accountNumberAlias + ''.'' + @accountNumberColName + '' = '''''' + @accountnumber + ''''''''
	end

	if ( @businessunit is not null and @businessunit != '''' ) begin
		if ( len(@filterclause) != 0 ) begin
			set @filterclause = @filterclause + '' and ''
		end
		set @filterClause = @filterClause + @businessUnitAlias + ''.businessunit = '''''' + @businessunit + ''''''''
	end
	

	if ( @periodends is not null ) begin
		if ( len(@filterclause) != 0 ) begin
			set @filterclause = @filterclause + '' and ''
		end
		if ( @usePeriodEndsLE = 1 ) begin
			set @peOp = ''<=''
		end
		set @filterClause = @filterClause + @periodEndsAlias + ''.periodends '' + @peOp + '' '''''' + convert(varchar(30),@periodends,101) + ''''''''
	end

	if ( @excludeCompanies is not null and @excludeCompanies != '''' ) begin
		if ( len(@filterclause) != 0 ) begin
			set @filterclause = @filterclause + '' and ''
		end
		set @filterClause = @filterClause + @companynumberalias + ''.'' + @companyNumberColName + '' not in ('' + @excludeCompanies + '')''
	end
	
	if ( @debug = 1 ) print @filterclause


END
	
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetStandardFilters] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetStandardUOMs]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetStandardUOMs]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2GetStandardUOMs]
AS
	--Select Distinct UMUM as UOM	From F41002 ORDER BY UMUM
	select UOM from RStandardUOMs order by UOM
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetStandardUOMs] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetSysVar]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetSysVar]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2GetSysVar]
	@VariableName varchar(50)
	,@VariableValue varchar(500) output
AS
/*
	declare @value varchar(500)
	exec usp2GetSysVar ''RefreshJobName'',@value output
	select @value
*/

	set nocount on

	select @VariableValue = isnull(value,'''') from dbo.RSystemVariables where [name] = @variablename

	set @VariableValue = isnull(@VariableValue,'''')

	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetSysVar] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetUnauthorizedCompanies]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetUnauthorizedCompanies]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create proc [dbo].[usp2GetUnauthorizedCompanies]
 @UserID char(10)
AS
/*
 exec usp2GetUnauthorizedCompanies
*/
	set nocount on

	select companynumber from rcompanies 
	where companynumber not in 
			(select companynumber from usercompany where userid = @UserID)
	Order By 	CompanyNumber

	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetUnauthorizedCompanies] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetUser]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetUser]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2GetUser] @UserID CHAR(10)

AS 

	set nocount on

    SELECT  Users.UserID, Users.Password, Users.usertypeid,ut.usertype, Users.active
    FROM    Users inner join dbo.userTypes ut on users.usertypeid = ut.usertypeid
    WHERE   UserID = @UserID

	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetUser] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2GetViewData]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2GetViewData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*******************************************************************************************************************/ 
CREATE PROCEDURE [dbo].[usp2GetViewData]
	 @table varchar(255)
	,@companyNumber varchar(5) = ''''
	,@accountnumber varchar(28) = ''''
	,@businessunit varchar(12) = ''''
	,@periodends smalldatetime = null
	,@excludeCompanies varchar(255) = null
	,@debug bit = 0
AS 
/*
	exec usp2getviewdata ''v_Report1_Open_Mfg'',''10220'',''102910003.116110'','''',@periodends=''3/31/06'',@excludecompanies=''10220,foo''

  exec usp2getviewdata 
		@table=''v_Report1_Open_Mfg''
	--, @periodends = ''2/28/07''
	, @excludecompanies = ''''
	, @debug = 1

  exec usp2getviewdata 
		@table=''v_Report1_Open_Mfg''
	--, @businessunit = ''11101000''
	, @periodends = ''3/31/07''
	, @excludecompanies = ''''
	, @debug = 1

  exec usp2getviewdata 
		@table=''v_Report6_Out_of_Balance''
	--, @businessunit = ''11101000''
	, @periodends = ''2/28/07''
	, @excludecompanies = ''''
	, @debug =1

  exec usp2getviewdata 
		@table=''v_Roll_Forward_Doc''
  , @companynumber = ''01551''
	, @businessunit = ''    15511000''
  , @accountnumber = ''15511000.1356  .000     ''
	, @periodends = ''3/31/07''
	, @excludecompanies = ''01300''
	, @debug = 1


	
	select * from rviewnames
*/
	set nocount on


	declare @sql nvarchar(4000)
	declare @where varchar(1024)
	declare @peLE bit
	set @peLe = 1
	if ( @table = ''v_Report6_Out_of_Balance'' ) begin
		set @peLE = 0
	end

	-- select
	set @sql = ''SELECT * from '' + @table + '' a''

	-- where
	exec usp2GetStandardFilters
		@companynumber=@companyNumber
	, @companynumberalias = ''a''
	, @companyNumberColName = ''company''
	, @accountnumber = @accountNumber
	, @accountnumberalias = ''a''
	, @accountnumbercolname = ''longaccount''
	, @businessunit = @businessunit
	, @businessunitalias = ''a''
	, @periodends = @periodends
	, @periodendsalias = ''a''
	, @usePeriodEndsLE = @peLE
	, @excludecompanies = @excludeCompanies
	, @filterClause = @where output
	
	if ( len(@where) > 0 ) begin
		set @sql = @sql + '' 
		WHERE '' + @where
	end

	-- table specific order clauses
	if ( @table = ''v_Report1_Open_Mfg'' ) begin
		set @sql = @sql + ''
		ORDER BY Company,
            PeriodEnds,
            LongAccount,
            BranchPlant,
            DocType,
            DocNumber''
	end
	if ( @table = ''v_Report2_Open_Sales'' ) begin
		set @sql = @sql + ''
    ORDER BY Company,
            PeriodEnds,
            LongAccount,
            BranchPlant,
            OrderType,
            OrderNumber''
	end
	if ( @table = ''v_Report3_Open_Batches'' ) begin
		set @sql = @sql + ''
    ORDER BY Company,
            PeriodEnds,
            LongAccount,
            BatchType,
            Batch''
	end
	if ( @table = ''v_Report4_GL_Roll_Forward'' ) begin
		set @sql = @sql + ''
    ORDER BY Company,
            LongAccount''
	end
	if ( @table = ''v_Report6_Out_of_Balance'' ) begin
		set @sql = @sql + ''
    ORDER BY PeriodEnds DESC,
            Company,
            LongAccount''
	end
	if ( @table = ''v_Report7_Manual_JE'' ) begin
		set @sql = @sql + ''
		ORDER BY GLCO,
            PeriodEnds,
            GLDCT,
            GLDOC,
            GLANI''
	end
	if ( @table = ''v_Roll_Forward_Doc'' ) begin
		set @sql = @sql + ''
			ORDER BY Company, 
							LongAccount, 
							PeriodEnds, 
							BeginningBalance, 
							DocType''
	end
	
	
	if ( @debug = 1 ) print ''['' + @sql + '']''
	exec sp_executeSQL @sql

	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2GetViewData] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2InsertCompaniesV3]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2InsertCompaniesV3]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE    Procedure [dbo].[usp2InsertCompaniesV3](@CompanyNumber CHAR(10),  
@PeriodCutoff datetime , @SubLedgerWO int, @AuthNumber int,  
@ExtCostDecimal int = 2, @SessionID Char(10)
) AS

	set nocount on

	Declare 		@Notes Varchar(100)

	Insert 		RCompanies (CompanyNumber, PeriodCutoff, SubLedgerWO, AuthNumber,ExtCostDecimal) 
	Values 		(@CompanyNumber, @PeriodCutoff, @SubLedgerWO, @AuthNumber,@ExtCostDecimal)
	Set 		@Notes = (Select RTrim(@SessionID) + '' Added '' + RTrim(@CompanyNumber) + '' Cutoff '' + Convert(Varchar(12),@PeriodCutoff) + '' Subledger '' + Convert(Varchar(1),@SubledgerWO) + '' ExtCostDecimal '' + convert(varchar,@ExtCostDecimal))
	Exec 		Update_Server_Log ''Company'', @Notes




-- Check to see if baseline exists and update RCompanies flag
If Exists(Select * From RBaselinePerpetual Where CompanyNumber = @CompanyNumber)
Begin 
Update RCompanies Set BaselineExist = 1 Where CompanyNumber = @CompanyNumber
End	


-- If Company Exists override start date
If Exists(Select * From RFiscalCalendar Where CompanyNumber = @CompanyNumber)

Begin 

Update RCompanies Set PeriodCutoff = (Select Min(PeriodBegins) From RFiscalCalendar Where CompanyNumber = @CompanyNumber)
Update RCompanies Set MaxPeriodEnds = (Select Max(PeriodEnds) From RFiscalCalendar Where CompanyNumber = @CompanyNumber)
Update RHome_Page_Flow Set PeriodEnds = (Select PeriodCutOff From RCompanies Where CompanyNumber = @CompanyNumber)


Update RCompanies Set FiscalYear = CDFY
From 		RCompanies
INNER JOIN	F0010 ON(CompanyNumber = CCCO)
INNER JOIN	vcr_F0008 ON (CCDTPN = CDDTPN AND CCDFYJ = CDDFYJ)
Where CompanyNumber = @CompanyNumber

End	


	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2InsertCompaniesV3] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2InsertUsers]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2InsertUsers]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2InsertUsers]
    ( @UserID CHAR(10),
      @Password CHAR(10),
      @UserTypeId int,
      @active BIT )
AS 

	set nocount on
    DECLARE @Notes VARCHAR(100)

    INSERT  Users
            ( UserID,
              Password,
              UserTypeId,
              active )
    VALUES  (
              @UserID,
              @Password,
              @UserTypeId,
              @active )

		declare @type varchar(50)
		set @type = (select usertype from usertypes where usertypeid = @usertypeid )
    SET @Notes = ( SELECT   ''Added User '' + RTRIM(@UserID) + '' Type '' + @Type )
    EXEC Update_Server_Log ''Users'', @Notes

	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2InsertUsers] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2ItemRollForward]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2ItemRollForward]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'


CREATE Procedure [dbo].[usp2ItemRollForward] (
	@BranchPlant nvarchar(12) = ''''
	,@itemnumber nvarchar(25) = ''''
	,@location nvarchar(20) = ''''
	,@lot nvarchar(30) = ''''
) As

set nocount on


---- Debug
-- exec usp2ItemRollForward

Declare @Format nchar(8)


-- Outside Operation Items
If @ItemNumber Like ''%*OP%'' 
Begin

Select @Format = ''OutOps''

	Select		@Format AS Display,
				A.CompanyNumber,
				'''' As LongAccount,
				BranchPlant,
				ItemNumber As Item,
				Location As Loc,
				Lot,
				0 As UKID,
				LastCompleteRun As TransDate,
				A.LastRec,
				'''' As DT,
				0 As Doc,
				Sum(QuantityOnHand) As Qty,
				0 As Cost,
				Sum(Cast(AmountOnHand As Decimal(18,2))) As Val,
				''End Bal'' As Comm,
				Sum(EstUnits) As QtyVar,
				Sum(BaselineVar) As AmtVar
	From		RPerpetualInv A	
	Inner Join	RTimestamp On (1=1)		
	Where		ltrim(BranchPlant) = ltrim(@BranchPlant) And ItemNumber = @Itemnumber And Location = @Location And Lot = @Lot
	Group By	A.CompanyNumber, BranchPlant, ItemNumber, Location, Lot, LastRec, LastCompleteRun
	Order By	UKID, BranchPlant, Item, Loc, Lot



GoTo Skip
End




-- Determine if only account is GL Class Not In Base Table or mixed
Declare @NonStock int
Select  @Nonstock = 0


-- Mixed accounts stock and nonstock
If Exists (Select * from rperpetualinv a 
			Where exists (Select * 
							from rperpetualinv b 
							where a.branchplant = b.branchplant and a.itemnumber = b.itemnumber and a.location = b.location and a.lot = b.lot and a.longaccount <> b.longaccount) 
							--and a.longaccount = ''GL Class not in Base Table''
							and ltrim(a.BranchPlant) = ltrim(@BranchPlant) And a.ItemNumber = @ItemNumber And A.Location = @Location And A.Lot = @Lot)
			Begin Select @Nonstock = 1 Select @Format = ''Mixed'' End	

			
-- Non Stock Only
If Exists (Select * from rperpetualinv a 
			Where not exists (Select * 
							from rperpetualinv b 
							where a.branchplant = b.branchplant and a.itemnumber = b.itemnumber and a.location = b.location and a.lot = b.lot and b.longaccount <> ''GL Class not in Base Table'') 
							and a.longaccount = ''GL Class not in Base Table''
							and ltrim(a.BranchPlant) = ltrim(@BranchPlant) And a.ItemNumber = @ItemNumber And A.Location = @Location And A.Lot = @Lot)
			Begin Select @Nonstock = 2 Select @Format = ''NonStk'' End				



-- Display proper format
-- If mixed accounts, stock and non-stock
If @NonStock = 1
Begin
	Select		@Format AS Display,
				A.CompanyNumber,
				'''' As LongAccount,
				A.BranchPlant,
				A.ItemNumber As Item,
				A.Location As Loc,
				A.Lot,
				0 As UKID,
				0 As TransDate,
				Min(A.PeriodEnds) As PeriodEnds,
				'''' As DT,
				0 As Doc,
				Sum(B.QuantityOnHand) As Qty,
				0 As Cost,
				Sum(Cast(B.AmountOnHand As Decimal(18,2))) As Val,
				''Beg Bal'' As Comm,
				0 As QtyVar,
				0 As AmtVar
	From		RInvAsOf A
	Inner Join	RBaselinePerpetual B On (A.LongAccount = B.LongAccount And A.BranchPlant = B.BranchPlant And A.ItemNumber = B.ItemNumber And A.Location = B.Location And A.Lot = B.Lot)			
	Where		PeriodBegins = ''1900-01-01 00:00:00'' And A.ItemNumber = @Itemnumber And ltrim(A.BranchPlant) = @BranchPlant And A.Location = @Location And A.Lot = @Lot
	Group By	A.CompanyNumber, A.BranchPlant, A.ItemNumber, A.Location, A.Lot 


Union

	Select      @Format AS Display,
				ILKCO As CompanyNumber,
				InventoryAccount,
				ILMCU As BranchPlant, 
				ILLITM As Item, 
				ILLOCN As Loc, 
				ILLOTN As Lot,
				ILUKID As UKID,
				ILTRDJ As TransDate,
				PeriodEnds,
				ILDCT As DT,
				ILDOC As Doc,
				ILTRQT As Qty,
				ILUNCS As Cost, 
				ILPAID As Val,
				'''' As Comm,
				0 As QtyVar,
				0 As AmtVar
	From  F4111B 
	Where ltrim(ILMCU) = ltrim(@BranchPlant) And ILLITM = @Itemnumber And ILLOCN = @Location And ILLOTN = @Lot


Union

	Select		@Format AS Display,
				A.CompanyNumber,
				'''' As LongAccount,
				BranchPlant,
				ItemNumber As Item,
				Location As Loc,
				Lot,
				9999999999 As UKID,
				LastCompleteRun As TransDate,
				MaxPeriodEnds As PeriodEnds,
				'''' As DT,
				0 As Doc,
				Sum(QuantityOnHand) As Qty,
				0 As Cost,
				Sum(Cast(AmountOnHand As Decimal(18,2))) As Val,
				''End Bal'' As Comm,
				Sum(EstUnits) As QtyVar,
				Sum(BaselineVar) As AmtVar
	From		RPerpetualInv A	
	Inner Join	RTimestamp On (1=1)
	Inner Join	Rcompanies B On (A.CompanyNumber = B.CompanyNumber)		
	Where		ltrim(BranchPlant) = ltrim(@BranchPlant) And ItemNumber = @Itemnumber And Location = @Location And Lot = @Lot
	Group By	A.CompanyNumber, BranchPlant, ItemNumber, Location, Lot, LastRec, LastCompleteRun, MaxPeriodEnds
	Order By	UKID, BranchPlant, Item, Loc, Lot

GoTo Skip
End



-- If Non Stock Only, No roll forward
If @NonStock = 2
Begin
	Select		@Format AS Display,
				A.CompanyNumber,
				'''' As LongAccount,
				BranchPlant,
				ItemNumber As Item,
				Location As Loc,
				Lot,
				0 As UKID,
				LastCompleteRun As TransDate,
				A.LastRec,
				'''' As DT,
				0 As Doc,
				Sum(QuantityOnHand) As Qty,
				UnitCost As Cost,
				Sum(Cast(AmountOnHand As Decimal(18,2))) As Val,
				''End Bal'' As Comm,
				Sum(EstUnits) As QtyVar,
				Sum(BaselineVar) As AmtVar
	From		RPerpetualInv A	
	Inner Join	RTimestamp On (1=1)		
	Where		ltrim(BranchPlant) = ltrim(@BranchPlant) And ItemNumber = @Itemnumber And Location = @Location And Lot = @Lot
	Group By	A.CompanyNumber, BranchPlant, ItemNumber, Location, Lot, LastRec, LastCompleteRun, UnitCost
	Order By	UKID, BranchPlant, Item, Loc, Lot
GoTo Skip
End

-- If item is a valid stock item, determine the cost level and method
-- There is a unique Display for average cost items however it will only be called if the cost method = 02, there is a quantity on hand, and cardex records exist
-- Otherwise the standard format will Display


-- Get Level
Declare @Level nvarchar(1)
Select  @Level = (Select Distinct CostLevel From RPerpetualInv Where ItemNumber = @ItemNumber)



-- Get Cost Method
Declare @Method nvarchar(2)
If @Level = 1 Begin Select @Method = (Select Distinct CostMethod From RPerpetualInv Where ItemNumber = @ItemNumber) End
If @Level = 2 Begin Select @Method = (Select Distinct CostMethod From RPerpetualInv Where ItemNumber = @ItemNumber And Ltrim(BranchPlant) = LTrim(@BranchPlant)) End
If @Level = 3 Begin Select @Method = (Select Distinct CostMethod From RPerpetualInv Where ItemNumber = @ItemNumber And Ltrim(BranchPlant) = LTrim(@BranchPlant) And Location = @Location And Lot = @Lot) End


-- If not an average cost item go to standard format
If @Method <> ''02'' Begin Select @Format = ''STD '' + @Method GoTo Standard End 


-- If average cost but there are no cardex records or quantity hand is zero, go to standard format
Select @Format = ''Avg0''
If @Level = 1 Begin If Not Exists (Select * From RAvgCostUpdate Where ItemNumber = @ItemNumber) GoTo Standard End
If @Level = 2 Begin If Not Exists (Select * From RAvgCostUpdate Where ItemNumber = @ItemNumber And Ltrim(BranchPlant) = LTrim(@BranchPlant)) GoTo Standard End
If @Level = 3 Begin If Not Exists (Select * From RAvgCostUpdate Where ItemNumber = @ItemNumber And Ltrim(BranchPlant) = LTrim(@BranchPlant) And Location = @Location And Lot = @Lot) GoTo Standard End



-- Average cost running calculation
-- Else Display average cost format
If @Level = ''1''
Begin
Select	Top 100 Percent
		''Avg1'' AS Display,
		AsOf,
		CostLevel,
		UKID,
		ShortItem, 
		ItemNumber,
		BranchPlant,
		Location,
		Lot,
		DocType,
		DocNumber,
		TransDate,
		UnitCost,
		Cast(Quantity AS Decimal(18,2)) As Quantity,
		ExtCost,
		PrevAvg,   
		CalcAvg,
		CurrCost, 
		Cast(PrevBal As Decimal(18,2)) As PrevBal,
		Cast(RunBal AS Decimal(18,2)) As RunBal,
		QOH, 
		Cast((CalcAvg - CurrCost)*QOH As Decimal(18,2)) As RevalAmt 
From	RAvgCostUpdate
Where	ItemNumber = @Itemnumber
Order By UKID, ItemNumber
GoTo Skip
End

If @Level = ''2''
Begin
Select	Top 100 Percent
		''Avg2'' AS Display,
		AsOf,
		CostLevel,
		UKID,
		ShortItem, 
		ItemNumber,
		BranchPlant,
		Location,
		Lot,
		DocType,
		DocNumber,
		TransDate,
		UnitCost,
		Cast(Quantity AS Decimal(18,2)) As Quantity,
		ExtCost,
		PrevAvg,   
		CalcAvg,
		CurrCost, 
		Cast(PrevBal As Decimal(18,2)) As PrevBal,
		Cast(RunBal AS Decimal(18,2)) As RunBal,
		QOH, 
		Cast((CalcAvg - CurrCost)*QOH As Decimal(18,2)) As RevalAmt 
From	RAvgCostUpdate
Where	ItemNumber = @Itemnumber And Ltrim(BranchPlant) = Ltrim(@BranchPlant)
Order By UKID, ItemNumber
GoTo Skip
End

If @Level = ''3''
Begin
Select	Top 100 Percent
		''Avg3'' AS Display,
		AsOf,
		CostLevel,
		UKID,
		ShortItem, 
		ItemNumber,
		BranchPlant As Branch,
		Location As Loc,
		Lot,
		DocType As DT,
		DocNumber As Doc,
		TransDate,
		UnitCost,
		Cast(Quantity AS Decimal(18,2)) As Quantity,
		ExtCost,
		PrevAvg,   
		CalcAvg,
		CurrCost, 
		Cast(PrevBal As Decimal(18,2)) As PrevBal,
		Cast(RunBal AS Decimal(18,2)) As RunBal,
		QOH, 
		Cast((CalcAvg - CurrCost)*QOH As Decimal(18,2)) As RevalAmt 
From	RAvgCostUpdate
Where	ItemNumber = @Itemnumber And LTrim(BranchPlant) = LTrim(@BranchPlant) And Location = @Location And Lot = @Lot
Order By UKID, ItemNumber
GoTo Skip
End


Standard:

-- If not average cost item, then use this format
	Select		@Format AS Display,
				A.CompanyNumber,
				'''' As LongAccount,
				BranchPlant,
				ItemNumber As Item,
				Location As Loc,
				Lot,
				0 As UKID,
				A.PeriodEnds As TransDate,
				A.PeriodEnds,
				'''' As DT,
				0 As Doc,
				Sum(QuantityOnHand) As Qty,
				Case When Sum(QuantityOnHand) <> 0 Then Cast(Sum(AmountOnHand)/Sum(QuantityOnHand) As Decimal(18,4)) Else 0 End As Cost,
				Cast(Sum(AmountOnHand) As Decimal(18,2)) As Val,
				''Beg Bal'' As Comm,
				0 As QtyVar,
				0 As AmtVar
	From		RInvAsOf A			
	Where		PeriodBegins = ''1900-01-01 00:00:00'' And ItemNumber = @Itemnumber And ltrim(BranchPlant) = @BranchPlant And Location = @Location And Lot = @Lot
	Group By	A.CompanyNumber, BranchPlant, ItemNumber, Location, Lot, A.PeriodEnds

Union

	Select      @Format AS Display,
				ILKCO As CompanyNumber,
				InventoryAccount,
				ILMCU As BranchPlant, 
				ILLITM As Item, 
				ILLOCN As Loc, 
				ILLOTN As Lot,
				ILUKID As UKID,
				ILTRDJ As TransDate,
				PeriodEnds,
				ILDCT As DT,
				ILDOC As Doc,
				ILTRQT As Qty,
				ILUNCS As Cost, 
				ILPAID As Val,
				'''' As Comm,
				0 As QtyVar,
				0 As AmtVar
	From  F4111B 
	Where ltrim(ILMCU) = ltrim(@BranchPlant) And ILLITM = @Itemnumber And ILLOCN = @Location And ILLOTN = @Lot


Union

	Select		@Format AS Display,
				A.CompanyNumber,
				'''' As LongAccount,
				BranchPlant,
				ItemNumber As Item,
				Location As Loc,
				Lot,
				9999999999 As UKID,
				LastRec As TransDate,
				MaxPeriodEnds As PeriodEnds,
				'''' As DT,
				0 As Doc,
				Sum(QuantityOnHand) As Qty,
				UnitCost As Cost,
				Cast( Sum(AmountOnHand) As Decimal(18,2)) As Val,
				''End Bal'' As Comm,
				Sum(EstUnits) As QtyVar,
				Sum(BaselineVar) As AmtVar
	From RPerpetualInv A	
	Inner Join RCompanies B On (A.CompanyNumber = B.CompanyNumber)		
	Where ltrim(BranchPlant) = ltrim(@BranchPlant) And ItemNumber = @Itemnumber And Location = @Location And Lot = @Lot
	Group By A.CompanyNumber, BranchPlant, ItemNumber, Location, Lot, LastRec, UnitCost, MaxPeriodEnds
	Order By	UKID

Skip:

	set nocount off

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2ItemRollForward] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2MaintainCardexLedgerCompareWorkNote]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2MaintainCardexLedgerCompareWorkNote]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[usp2MaintainCardexLedgerCompareWorkNote] 
	 @CompanyNumber varchar(5)
	,@InventoryAccount varchar(29)
	,@OrderType varchar(6)
	,@DocType varchar(2)
	,@DocNumber decimal(8, 0)
	,@PeriodEnds smalldatetime
	,@MfgBatch decimal(8, 0)
	,@Worked bit
	,@Note varchar(5000)
	,@LastModifiedBy varchar(50)
	,@LastModifiedDate smalldatetime = NULL
AS
/*
exec usp2MaintainCardexLedgerCompareWorkNote
 ''01002''
,''10021000.1351  .002     ''
,''WO''
,''IM''
,798245
,''2007-03-31 00:00:00''
,3541212
,0
,''a note here''

select top 100 * from dbo.RCardexLedgerCompare2
select * from RCardexLedgerCompare2WorkNote
*/
BEGIN
	SET NOCOUNT ON;

	-- default lmd
	if ( @LastModifiedDate is null ) begin
		set @LastModifiedDate = GetDate()
	end

  -- upsert
	update [RCardexLedgerCompare2WorkNote]
	set Worked = @Worked
		,Note = @Note
		,LastModifiedBy = @LastModifiedBy
		,LastModifiedDate = @LastModifiedDate
	where
		CompanyNumber = @CompanyNumber
		and InventoryAccount = @InventoryAccount
		and OrderType = @OrderType
		and DocType = @DocType
		and DocNumber = @DocNumber
		and PeriodEnds = @PeriodEnds
		and MfgBatch = @MfgBatch
		
	if ( @@RowCount = 0 ) begin
		insert [RCardexLedgerCompare2WorkNote]
		values (@CompanyNumber,@InventoryAccount,@OrderType,@DocType,@DocNumber,@PeriodEnds,@MfgBatch,@Worked,@Note,@LastModifiedBy,@LastModifiedDate)
	end

	set nocount off
END
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2MaintainCardexLedgerCompareWorkNote] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2RefreshRunning]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2RefreshRunning]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2RefreshRunning]
AS
/*
	This procedure REQUIRES the executing user be in the SQLAgentOperatorRole
	of the msdb database.

	declare @ret int
	exec @ret = usp2RefreshRunning
	select @ret

delete from RSystemVariables where name = ''RefreshJobName''

*/

	set nocount on

	declare @ret int
	declare @txt varchar(1000)

--	-- make sure sql server agent is running
--	create table #state ( state varchar(2000) )
--	declare @AgentState varchar(2000)
--	insert into #state EXEC master.dbo.xp_ServiceControl ''QUERYSTATE'',''SQLServerAgent''
--	set @AgentState = (select top 1 state from #state)
--	drop table #state
--
--	if ( @AgentState != ''Running.'' ) begin
--		return -1
--	end

	-- get job name
	declare @RefreshJobName varchar(500)
	exec dbo.usp2GetSysVar ''RefreshJobName'', @RefreshJobName output
	if ( @@error <> 0 ) begin
		raiserror (''The SQL user must be in the SQLAgentOperatorRole in the msdb database of the server.'',10,1)
		return 0
	end

	if ( @RefreshJobName = '''' ) begin
		raiserror (''The JDE Import job name was not found in RSystemVariables. The key is [RefreshJobName]. Unable to check current job status.'',10,1)
		return 0
	end

	-- get job uid
	declare @jobId uniqueidentifier
	set @jobId = (select job_id from msdb.dbo.sysjobs_view where name=@RefreshJobName)
	if ( @@error <> 0 ) begin
		raiserror (''The SQL user must be in the SQLAgentOperatorRole in the msdb database of the server.'',10,1)
		return 0
	end

	if ( @jobId is null ) begin
		set @txt = ''The JDE Import job name in RSystemVariables ('' + @RefreshJobName + '') matched no jobs on this server. Unable to check current job status.''
		raiserror (@txt,10,1)
		return 0
	end	

	-- can''t do insert into from sproc with table var
	create table #enum_job (
		Job_ID uniqueidentifier, 
		Last_Run_Date int, 
		Last_Run_Time int, 
		Next_Run_Date int, 
		Next_Run_Time int, 
		Next_Run_Schedule_ID int, 
		Requested_To_Run int, 
		Request_Source int, 
		Request_Source_ID varchar(100), 
		Running int, 
		Current_Step int, 
		Current_Retry_Attempt int, 
		State int 
	)

	insert into #enum_job exec master.dbo.xp_sqlagent_enum_jobs 1,garbage  
	if ( @@error <> 0 ) begin
		raiserror (''The SQL user must be in the SQLAgentOperatorRole in the msdb database of the server.'',10,1)
	end	

	select @ret = running from #enum_job where job_id = @jobId
	

	drop table #enum_job

	return isnull(@ret,0)

	set nocount off

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2RefreshRunning] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2StartRefresh]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2StartRefresh]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2StartRefresh]
	
AS
/*
	This procedure REQUIRES the executing user be in the SQLAgentOperatorRole
	of the msdb database.

	declare @ret int
	exec @ret = usp2StartRefresh
	select started=@ret
	waitfor delay ''00:00:01''
	exec @ret = usp2RefreshRunning
	select isrunning=@ret	

	exec master.dbo.xp_sqlagent_enum_jobs 1,garbage  
*/

set nocount on

	declare @ret int

	-- don''t start if running
	declare @isRunning int
	exec @isRunning = dbo.usp2RefreshRunning

	if ( @isRunning = 0 ) begin
		-- start it
		declare @RefreshJobName varchar(500)
		exec dbo.usp2GetSysVar ''RefreshJobName'', @RefreshJobName output
		exec @ret = msdb.dbo.sp_start_job @job_name=@RefreshJobName
		-- start_job return 0 if success, 1 if failure, we want to return 1 if job started
		if ( @ret = 0 ) begin
			set @ret = 1
		end else begin
			set @ret = 0
		end
	end
	else begin
		set @ret = 0
	end

	return @ret

set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2StartRefresh] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2UpdateCompanyV3]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2UpdateCompanyV3]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2UpdateCompanyV3]
    ( @CompanyNumber VARCHAR(5),
      @PeriodCutoff SMALLDATETIME,
      @SubledgerWO INT,
      @ExtCostDecimal INT,
      @SessionID CHAR(10) )
AS 
/*

	exec usp2updatecompanyv3 @companynumber=''foo'',@periodcutoff=''2/15/07'',@subledgerwo=0,@extcostdecimal=9999,@sessionid=''admin''

*/
	set nocount on

    DECLARE @CurrentCutoff SMALLDATETIME
    DECLARE @Notes VARCHAR(100)
    DECLARE @SL INT
    DECLARE @CurrentDecimal INT

    SET @CurrentCutoff = ( SELECT   PeriodCutoff
                           FROM     RCompanies
                           WHERE    CompanyNumber = @CompanyNumber )
    SET @SL = ( SELECT  SubledgerWO
                FROM    RCompanies
                WHERE   CompanyNumber = @CompanyNumber )
    SET @CurrentDecimal = ( SELECT  ExtCostDecimal
                            FROM    RCompanies
                            WHERE   CompanyNumber = @CompanyNumber )


    IF @PeriodCutoff  < @CurrentCutoff AND
        @CurrentCutoff IS NOT NULL 
        BEGIN
		
            UPDATE  RCompanies
            SET     BaselineExist = 8
            WHERE   CompanyNumber = @CompanyNumber

            SET @Notes = ( SELECT   RTRIM(@SessionID) + '' Changed Cutoff '' + @CompanyNumber + '' From '' + CONVERT(VARCHAR(12), @CurrentCutoff) + '' To '' + CONVERT(VARCHAR(12), @PeriodCutoff) )
            EXEC Update_Server_Log ''Company'', @Notes
        END




    IF @PeriodCutoff  > @CurrentCutoff AND
        @CurrentCutoff IS NOT NULL 
        BEGIN
		
            UPDATE  RCompanies
            SET     BaselineExist = 0
            WHERE   CompanyNumber = @CompanyNumber

            SET @Notes = ( SELECT   RTRIM(@SessionID) + '' Changed Cutoff '' + @CompanyNumber + '' From '' + CONVERT(VARCHAR(12), @CurrentCutoff) + '' To '' + CONVERT(VARCHAR(12), @PeriodCutoff) )
            EXEC Update_Server_Log ''Company'', @Notes
        END



    IF @SL <> @SubledgerWO 
        BEGIN
            SET @Notes = ( SELECT   RTRIM(@SessionID) + '' Changed SL '' + @CompanyNumber + '' From '' + CONVERT(VARCHAR(12), @SL) + '' To '' + CONVERT(VARCHAR(12), @SubledgerWO) )
            EXEC Update_Server_Log ''Company'', @Notes
        END

    UPDATE  RCompanies
    SET     SubledgerWO = @SubledgerWO,
            PeriodCutoff = @PeriodCutoff
    WHERE   CompanyNumber = @CompanyNumber



    IF @CurrentDecimal <> @ExtCostDecimal 
        BEGIN
            SET @Notes = ( SELECT   RTRIM(@SessionID) + '' Changed Decimals'' + @CompanyNumber + '' From '' + CONVERT(VARCHAR(12), @CurrentDecimal) + '' To '' + CONVERT(VARCHAR(12), @ExtCostDecimal) )
            EXEC Update_Server_Log ''Company'', @Notes
        END

    UPDATE  RCompanies
    SET     SubledgerWO = @SubledgerWO,
            PeriodCutoff = @PeriodCutoff,
            ExtCostDecimal = @ExtCostDecimal
    WHERE   CompanyNumber = @CompanyNumber

	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2UpdateCompanyV3] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2UpdateConstantsV3]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2UpdateConstantsV3]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create Procedure [dbo].[usp2UpdateConstantsV3](@AAITableNum INT, @AAIDocType CHAR(2), @UnitCostDecimal INT, 
					  @InventoryDecimal INT, @Threshold1 float, @Threshold2 float, @SessionID Char(10),
					  @XFerSOType CHAR(2),  @XFerPOType CHAR(2), @DirSOType CHAR(2),  @DirPOType CHAR(2), 
					  @OOPOType CHAR(2), @CXDaysBack Int) AS

set nocount on


Declare	@OldTable Int, @OldType Char(2), @OldUnit Int, @OldExt Int, @OldInv Int, @OldT1 float, @OldT2 float, @OldXferSO Char(2),
	@OldXferPO Char(2), @OldDirSO Char(2), @OldDirPO Char(2), @OldOOPO Char(2), @OldCXDaysBack Int

Declare @Notes Varchar(100), @@Step Varchar(30), @@Process Varchar(100)

Set	@@Step = ''Constants''

Set	@OldTable = (Select AAITableNum from RConstants)
Set	@OldType = (Select AAIDocType from RConstants)
Set	@OldUnit = (Select UnitCostDecimal from RConstants)
Set	@OldInv = (Select InventoryDecimal from RConstants)
Set	@OldT1 = (Select Threshold1 from RConstants)
Set	@OldT2 = (Select Threshold2 from RConstants)
Set	@OldXferSO = (Select XferSOType from RConstants)
Set	@OldXferPO = (Select XferPOType from RConstants)
Set	@OldDirSO = (Select DirSOType from RConstants)
Set	@OldDirPO = (Select DirPOType from RConstants)
Set	@OldOOPO = (Select OOPOType from RConstants)
Set	@OldCXDaysBack = (Select CXDaysBack from RConstants)




If	@OldTable <> @AAITableNum
Begin
	Set @Notes = (Select RTrim(@SessionID) + '' Changed Table From '' + Convert(Varchar(6),@OldTable) + '' To '' + Convert(Varchar(6),@AAITableNum))
	Exec Update_Server_Log @@Step, @Notes
End

If	@OldType <> @AAIDocType
Begin
	Set @Notes = (Select RTrim(@SessionID)  + '' Changed DocType From '' + Convert(Varchar(6),@OldType) + '' To '' + Convert(Varchar(6),@AAIDocType))
	Exec Update_Server_Log @@Step, @Notes
End

If	@OldUnit <> @UnitCostDecimal
Begin
	Set @Notes = (Select RTrim(@SessionID)  + '' Changed Unit Cost Decimals From '' + Convert(Varchar(6),@OldUnit) + '' To '' + Convert(Varchar(6),@UnitCostDecimal))
	Exec Update_Server_Log @@Step, @Notes
End


If	@OldInv <> @InventoryDecimal
Begin
	Set @Notes = (Select RTrim(@SessionID)  + '' Changed Inventory Decimals From '' + Convert(Varchar(6),@OldInv) + '' To '' + Convert(Varchar(6),@InventoryDecimal))
	Exec Update_Server_Log @@Step, @Notes
End

If	@OldT1 <> @Threshold1
Begin
	Set @Notes =  (Select RTrim(@SessionID)  + '' Changed Threshold1 From '' + Convert(Varchar(6),@OldT1) + '' To '' + Convert(Varchar(6),@Threshold1))
	Exec Update_Server_Log @@Step, @Notes
End

If	@OldT2 <> @Threshold2
Begin
	Set @Notes = (Select RTrim(@SessionID)  + '' Changed Threshold2 From '' + Convert(Varchar(6),@OldT2) + '' To '' + Convert(Varchar(6),@Threshold2))
	Exec Update_Server_Log @@Step, @Notes
End


If	@OldXferSO <> @XferSOType
Begin
	Set @Notes = (Select RTrim(@SessionID)  + '' Changed XferSOType From '' + Convert(Varchar(6),@OldXferSO) + '' To '' + Convert(Varchar(6),@XferSOType))
	Exec Update_Server_Log @@Step, @Notes
End

If	@OldXferPO <> @XferPOType
Begin
	Set @Notes = (Select RTrim(@SessionID)  + '' Changed XferPOType From '' + Convert(Varchar(6),@OldXferPO) + '' To '' + Convert(Varchar(6),@XferPOType))
	Exec Update_Server_Log @@Step, @Notes
End

If	@OldDirSO <> @DirSOType
Begin
	Set @Notes = (Select RTrim(@SessionID)  + '' Changed DirSOType From '' + Convert(Varchar(6),@OldDirSO) + '' To '' + Convert(Varchar(6),@DirSOType))
	Exec Update_Server_Log @@Step, @Notes
End

If	@OldDirPO <> @DirPOType
Begin
	Set @Notes = (Select RTrim(@SessionID)  + '' Changed DirPOType From '' + Convert(Varchar(6),@OldDirPO) + '' To '' + Convert(Varchar(6),@DirPOType))
	Exec Update_Server_Log @@Step, @Notes
End

If	@OldOOPO <> @OOPOType
Begin

	Set @Notes = (Select RTrim(@SessionID)  + '' Changed OOPOType From '' + Convert(Varchar(6),@OldOOPO) + '' To '' + Convert(Varchar(6),@OOPOType))
	Exec Update_Server_Log @@Step, @Notes
End


If 	@CXDaysBack <= 0 Begin Set @CXDaysBack = 1 End

If	@OldCXDaysBack <> @CXDaysBack
Begin
	Set @Notes = (Select RTrim(@SessionID)  + '' Changed CXDaysBack From '' + Convert(Varchar(6),@OldCXDaysBack) + '' To '' + Convert(Varchar(6),@CXDaysBack))
	Exec Update_Server_Log @@Step, @Notes
End


Update  RConstants
Set   	AAITableNum =@AAITableNum, 
	AAIDocType =@AAIDocType, 
	UnitCostDecimal =@UnitCostDecimal, 	
	InventoryDecimal =@InventoryDecimal, 
	Threshold1 =@Threshold1, 
	Threshold2 =@Threshold2,
	XferSOType = @XferSOType,
	XferPOType = @XferPOType,
	DirSOType = @DirSOType,
	DirPOType = @DirPOType,
	OOPOType = @OOPOType,
	CXDaysBack = @CXDaysBack

set nocount off

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2UpdateConstantsV3] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp2UpdateUsers]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp2UpdateUsers]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[usp2UpdateUsers]
    ( @UserID CHAR(10),
      @Password CHAR(10),
      @UserTypeID int,
      @active BIT,
      @SessionID CHAR(10) )
AS 
/*
	exec usp2getalluser
	exec usp2UpdateUsers ''user'',''user2'',''User'',1,''admin''

*/
	set nocount on

    DECLARE @OldPassword CHAR(10),
        @OldType varchar(50),
				@NewType varchar(50),
        @OldStatus BIT
    DECLARE @Notes VARCHAR(100)

    SET @OldPassword = ( SELECT Password
                         FROM   Users
                         WHERE  UserID = @UserID )
    SET @OldType = ( SELECT ut.usertype
                     FROM   Users u inner join usertypes ut on u.usertypeid = ut.usertypeid
                     WHERE  UserID = @UserID )
		set @NewType = ( select usertype from usertypes where usertypeid = @usertypeid )
    SET @OldStatus = ( SELECT   active
                       FROM     Users
                       WHERE    UserID = @UserID )

    IF @OldPassword <> @Password 
        BEGIN
            SET @Notes = ( SELECT   @SessionID + '' Changed '' + @UserID + '' Password From '' + CONVERT(VARCHAR(6), @OldPassword) + '' To '' + CONVERT(VARCHAR(6), @Password) )
            EXEC Update_Server_Log ''Users'', @Notes
        END

    IF @OldType <> @NewType 
        BEGIN
            SET @Notes = ( SELECT   @SessionID + '' Changed '' + @UserID + '' Type From '' + @OldType + '' To '' + @NewType )
            EXEC Update_Server_Log ''Users'', @Notes
        END


    IF @OldStatus <> @active 
        BEGIN
            SET @Notes = ( SELECT   @SessionID + '' Changed '' + @UserID + '' Status From '' + CONVERT(VARCHAR(6), @OldStatus) + '' To '' + CONVERT(VARCHAR(6), @active) )
            EXEC Update_Server_Log ''Users'', @Notes
        END


    UPDATE  Users
    SET     Password = @Password,
            usertypeid = @usertypeid,
            active = @active
    WHERE   UserID = @UserID

	set nocount off
' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp2UpdateUsers] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp3_Create_F4111B_Indexes]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp3_Create_F4111B_Indexes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

Create Procedure [dbo].[usp3_Create_F4111B_Indexes] As

DECLARE @Err INT, @@Step VARCHAR(30), @@Message VARCHAR(255), @@Process VARCHAR(100), @rowc INT
SET @Err = 0
SET @@Step = ''Create F4111B Indexes''



/****** Object:  Index [_dta_index_F4111B_30_2102402659__K2_K6_K37_K8_K9]    Script Date: 05/06/2011 07:07:20 ******/
IF  Not EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''_dta_index_F4111B_30_2102402659__K2_K6_K37_K8_K9'')

SET @@Process = ''Creating F4111B Index 30''
EXEC Update_Server_Log @@Step, @@Process

CREATE NONCLUSTERED INDEX [_dta_index_F4111B_30_2102402659__K2_K6_K37_K8_K9] ON [dbo].[F4111B] 
(
	[ILKCO] ASC,
	[ILMCU] ASC,
	[ILITM] ASC,
	[ILLOCN] ASC,
	[ILLOTN] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]




/****** Object:  Index [_dta_index_F4111B_TREX]    Script Date: 05/06/2011 07:09:01 ******/
IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''_dta_index_F4111B_TREX'')

SET @@Process = ''Creating F4111B Index TREX''
EXEC Update_Server_Log @@Step, @@Process

CREATE NONCLUSTERED INDEX [_dta_index_F4111B_TREX] ON [dbo].[F4111B] 
(
	[ILTREX] ASC,
	[ILDCT] ASC,
	[ILKCO] ASC,
	[ILDOC] ASC,
	[ILDCTO] ASC,
	[ILDOCO] ASC,
	[ILLNID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]



/****** Object:  Index [F4111B_Account]    Script Date: 05/06/2011 07:09:45 ******/
IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_Account'')

SET @@Process = ''Creating F4111B Index Account''
EXEC Update_Server_Log @@Step, @@Process

CREATE NONCLUSTERED INDEX [F4111B_Account] ON [dbo].[F4111B] 
(
	[ILKCO] ASC,
	[InventoryAccount] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]





/****** Object:  Index [F4111B_Document]    Script Date: 05/06/2011 07:10:25 ******/
IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_Document'')

SET @@Process = ''Creating F4111B Index Document''
EXEC Update_Server_Log @@Step, @@Process

CREATE NONCLUSTERED INDEX [F4111B_Document] ON [dbo].[F4111B] 
(
	[ILKCO] ASC,
	[InventoryAccount] ASC,
	[PeriodEnds] ASC,
	[ILDCT] ASC,
	[ILDOC] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]




/****** Object:  Index [F4111B_GLClass]    Script Date: 05/06/2011 07:11:26 ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_GLClass'')

SET @@Process = ''Creating F4111B Index GLClass''
EXEC Update_Server_Log @@Step, @@Process

CREATE NONCLUSTERED INDEX [F4111B_GLClass] ON [dbo].[F4111B] 
(
	[ILKCO] ASC,
	[ILGLPT] ASC,
	[ILMCU] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]



/****** Object:  Index [F4111B_Interco]    Script Date: 05/06/2011 07:12:02 ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_Interco'')

SET @@Process = ''Creating F4111B Index Interco''
EXEC Update_Server_Log @@Step, @@Process

CREATE NONCLUSTERED INDEX [F4111B_Interco] ON [dbo].[F4111B] 
(
	[ILKCOO] ASC,
	[ILKCO] ASC,
	[ILDCT] ASC,
	[ILDOC] ASC,
	[ILDCTO] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]




/****** Object:  Index [F4111B_InvAsOf]    Script Date: 05/06/2011 07:13:00 ******/
IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_InvAsOf'')

SET @@Process = ''Creating F4111B Index InvAsOf''
EXEC Update_Server_Log @@Step, @@Process

CREATE NONCLUSTERED INDEX [F4111B_InvAsOf] ON [dbo].[F4111B] 
(
	[ILLITM] ASC,
	[ILLOCN] ASC,
	[ILLOTN] ASC,
	[ILKCO] ASC,
	[ILDGL] ASC
)
INCLUDE ( [ILDCT],
[ILDOC],
[ILMCU],
[ILTRDJ],
[ILPAID],
[PeriodEnds],
[InventoryAccount],
[ILUKID],
[ILUNCS],
[ILTRQT]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]




/****** Object:  Index [F4111B_Item]    Script Date: 05/06/2011 07:14:22 ******/
IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_Item'')

SET @@Process = ''Creating F4111B Index Item''
EXEC Update_Server_Log @@Step, @@Process

CREATE NONCLUSTERED INDEX [F4111B_Item] ON [dbo].[F4111B] 
(
	[ILITM] ASC,
	[ILLITM] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]




/****** Object:  Index [F4111B_Order]    Script Date: 05/06/2011 07:15:01 ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_Order'')


SET @@Process = ''Creating F4111B Index Order''
EXEC Update_Server_Log @@Step, @@Process

CREATE NONCLUSTERED INDEX [F4111B_Order] ON [dbo].[F4111B] 
(
	[ILKCO] ASC,
	[ILDCTO] ASC,
	[ILDOCO] ASC,
	[ILLNID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]



/****** Object:  Index [F4111B_Prime]    Script Date: 05/06/2011 07:16:50 ******/
IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_Prime'')

SET @@Process = ''Creating F4111B Index Prime''
EXEC Update_Server_Log @@Step, @@Process

CREATE NONCLUSTERED INDEX [F4111B_Prime] ON [dbo].[F4111B] 
(
	[PrimeFlag] ASC,
	[ILITM] ASC,
	[ILMCU] ASC,
	[ILTRUM] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp3_Create_F4111B_Indexes] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp3_Drop_F4111B_Indexes]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp3_Drop_F4111B_Indexes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

CREATE Procedure [dbo].[usp3_Drop_F4111B_Indexes] As

DECLARE @Err INT, @@Step VARCHAR(30), @@Message VARCHAR(255), @@Process VARCHAR(100), @rowc INT
SET @Err = 0
SET @@Step = ''Drop F4111B Indexes''



/****** Object:  Index [_dta_index_F4111B_30_2102402659__K2_K6_K37_K8_K9]    Script Date: 05/06/2011 07:00:38 ******/
SET @@Process = ''Dropping F4111B Index 30''
EXEC Update_Server_Log @@Step, @@Process
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''_dta_index_F4111B_30_2102402659__K2_K6_K37_K8_K9'')
DROP INDEX [_dta_index_F4111B_30_2102402659__K2_K6_K37_K8_K9] ON [dbo].[F4111B] WITH ( ONLINE = OFF )


/****** Object:  Index [_dta_index_F4111B_TREX]    Script Date: 05/06/2011 07:00:55 ******/
SET @@Process = ''Dropping F4111B TREX''
EXEC Update_Server_Log @@Step, @@Process
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''_dta_index_F4111B_TREX'')
DROP INDEX [_dta_index_F4111B_TREX] ON [dbo].[F4111B] WITH ( ONLINE = OFF )

/****** Object:  Index [F4111B_Account]    Script Date: 05/06/2011 07:01:14 ******/
SET @@Process = ''Dropping F4111B Index Account''
EXEC Update_Server_Log @@Step, @@Process
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_Account'')
DROP INDEX [F4111B_Account] ON [dbo].[F4111B] WITH ( ONLINE = OFF )

/****** Object:  Index [F4111B_Document]    Script Date: 05/06/2011 07:01:38 ******/
SET @@Process = ''Dropping F4111B Index Document''
EXEC Update_Server_Log @@Step, @@Process
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_Document'')
DROP INDEX [F4111B_Document] ON [dbo].[F4111B] WITH ( ONLINE = OFF )

/****** Object:  Index [F4111B_GLClass]    Script Date: 05/06/2011 07:02:24 ******/
SET @@Process = ''Dropping F4111B Index GLClass''
EXEC Update_Server_Log @@Step, @@Process
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_GLClass'')
DROP INDEX [F4111B_GLClass] ON [dbo].[F4111B] WITH ( ONLINE = OFF )


/****** Object:  Index [F4111B_Interco]    Script Date: 05/06/2011 07:02:51 ******/
SET @@Process = ''Dropping F4111B Index Interco''
EXEC Update_Server_Log @@Step, @@Process
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_Interco'')
DROP INDEX [F4111B_Interco] ON [dbo].[F4111B] WITH ( ONLINE = OFF )


/****** Object:  Index [F4111B_InvAsOf]    Script Date: 05/06/2011 07:03:09 ******/
SET @@Process = ''Dropping F4111B Index InvAsOf''
EXEC Update_Server_Log @@Step, @@Process
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_InvAsOf'')
DROP INDEX [F4111B_InvAsOf] ON [dbo].[F4111B] WITH ( ONLINE = OFF )


/****** Object:  Index [F4111B_Item]    Script Date: 05/06/2011 07:03:25 ******/
SET @@Process = ''Dropping F4111B Index Item''
EXEC Update_Server_Log @@Step, @@Process
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_Item'')
DROP INDEX [F4111B_Item] ON [dbo].[F4111B] WITH ( ONLINE = OFF )


/****** Object:  Index [F4111B_Order]    Script Date: 05/06/2011 07:04:15 ******/

SET @@Process = ''Dropping F4111B Index Order''
EXEC Update_Server_Log @@Step, @@Process
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_Order'')
DROP INDEX [F4111B_Order] ON [dbo].[F4111B] WITH ( ONLINE = OFF )



/****** Object:  Index [F4111B_Prime]    Script Date: 05/06/2011 07:05:00 ******/
SET @@Process = ''Dropping F4111B Index Prime''
EXEC Update_Server_Log @@Step, @@Process
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].[F4111B]'') AND name = N''F4111B_Prime'')
DROP INDEX [F4111B_Prime] ON [dbo].[F4111B] WITH ( ONLINE = OFF )

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp3_Drop_F4111B_Indexes] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp3_reset_item_roll]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp3_reset_item_roll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
Create Procedure	[dbo].[usp3_reset_item_roll] ( @Err INT OUTPUT ) As

-- The purpose of this procedure is to reset the item roll for quantity variance after RR is run the SECOND TIME ONLY.
-- This will eliminate items with quantity variance from falsely appearing in the item roll integrity Box 2 report.
-- The procedure must be launched manually after the second cycle of RR, whether after initial install or reset.
-- This only needs to be done if the initial cycle cannot be done during system quiet time, eg 24x7 operations.

DECLARE @@Step VARCHAR(30), @@Process VARCHAR(100), @rowc INT,  @Check INT, @Company VarChar(5)
SET @@Step =	''Maintenance''
SET @@Process = ''Reset Item Roll Integrity QVAR''
EXEC Update_Server_Log @@Step, @@Process


Update		RBaselinePerpetual
Set			AmountOnHand = B.AmountOnHand,
			AmountInCardex = B.AmountInCardex,
			QuantityonHand = B.QuantityonHand,
			QuantityinCardex = B.QuantityinCardex
From		RBaselinePerpetual	A
Inner Join	RPerpetualInv		B On (A.CompanyNumber = B.CompanyNumber And A.LongAccount = B.LongAccount And A.BranchPlant = B.BranchPlant And A.ShortItem = B.ShortItem And A.Location = B.Location And A.Lot =B.Lot)
Where		Abs(B.EstUnits) > 0


Update		RBaseline
Set			SumCardex = CardexAmount,
			SumPerpetual = AmountOnHand
From		RBaseline A,
			(Select LongAccount, SUM(AmountinCardex) As CardexAmount, SUM(AmountonHand)As AmountOnHand From RBaselinePerpetual Group By LongAccount) As B
Where		A.LongAccount = B.LongAccount
			

UPDATE		RBaseline
SET			BaselineAOH = SumPerpetual - SumCardex
FROM		RBaseline BL


UPDATE		RBaseline
SET			BaselineVar = BaselineAOH - EndingGLBalance
FROM		RBaseline


UPDATE		RBaseline
SET			SumCardex = ROUND(SumCardex, 2),
			SumPerpetual = ROUND(SumPerpetual, 2),
			BaselineAOH = ROUND(BaselineAOH, 2),
			BaselineVAR = ROUND(BaselineVAR, 2)
FROM		RBaseline A 

	--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler



-- Successful Completion
SET		@@Process = ''Procedure completed sucessfully''
EXEC 	Update_Server_Log @@Step, @@Process  
    RETURN 0


-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 )
    RETURN -1
--End

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp3_reset_item_roll] TO  SCHEMA OWNER 
GO
/****** Object:  StoredProcedure [dbo].[usp3_reset_item_roll_item]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp3_reset_item_roll_item]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

Create procedure [dbo].[usp3_reset_item_roll_item] 
@Branch nvarchar(12)= '''',
@ItemNumber nVarchar(25) = '''',
@Location nVarchar(20)= '''',
@Lot nVarchar(30)= '''',
@Err INT OUTPUT  As
  
DECLARE @@Step VARCHAR(30), @@Process VARCHAR(100), @rowc INT,  @Check INT, @Company VarChar(5)
SET @@Step =	''Maintenance''
SET @@Process = ''Reset variance''
EXEC Update_Server_Log @@Step, @@Process
  
  
SET @@Process = ''New baseline for item '' + @itemnumber
EXEC Update_Server_Log @@Step, @@Process

	Delete From RBaselinePerpetual
	Where BranchPlant = @Branch And ItemNumber = @ItemNumber And Location = @Location And Lot = @Lot


    INSERT  INTO RBaselinePerpetual
            SELECT  A.CompanyNumber, A.LongAccount, A.BranchPlant, A.ShortItem, A.ItemNumber, A.Location, A.Lot,
                    A.AmountOnHand, A.AmountInCardex, A.QuantityOnHand, A.QuantityinCardex, IMUOM1, 0, 0, '''', 0, 0, 8
            FROM    RPerpetualInv A 
			Inner Join vcr_F4101 On (A.ShortItem = IMITM)
            WHERE   BranchPlant = @Branch And ItemNumber = @ItemNumber And Location = @Location And Lot = @Lot

	--Transaction logging		
SELECT  @err = @@error, @rowc = @@rowcount
EXEC sp_Update_Trans_Results @@Step, @@Process, @rowc, @err
IF @err <> 0 GOTO Err_Handler



Update		RBaseline
Set			SumCardex = CardexAmount,
			SumPerpetual = AmountOnHand
From		RBaseline A,
			(Select LongAccount, SUM(AmountinCardex) As CardexAmount, SUM(AmountonHand)As AmountOnHand From RBaselinePerpetual Group By LongAccount) As B
Where		A.LongAccount = B.LongAccount
			

UPDATE		RBaseline
SET			BaselineAOH = SumPerpetual - SumCardex
FROM		RBaseline BL


UPDATE		RBaseline
SET			BaselineVar = BaselineAOH - EndingGLBalance
FROM		RBaseline


UPDATE		RBaseline
SET			SumCardex = ROUND(SumCardex, 2),
			SumPerpetual = ROUND(SumPerpetual, 2),
			BaselineAOH = ROUND(BaselineAOH, 2),
			BaselineVAR = ROUND(BaselineVAR, 2)
FROM		RBaseline A 
   
    -- Successful Completion
SET		@@Process = ''Procedure completed sucessfully''
EXEC 	Update_Server_Log @@Step, @@Process  
    RETURN 0


-- Error Handling
    Err_Handler:
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ''RapidReconciler Error '' + @@Step + '' '' + @@Process
    RAISERROR ( @ErrorMessage, 16, 1 )
    RETURN -1
--End

' 
END
GO
ALTER AUTHORIZATION ON [dbo].[usp3_reset_item_roll_item] TO  SCHEMA OWNER 
GO
/****** Object:  UserDefinedFunction [dbo].[Convert_Primary_UOM]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Convert_Primary_UOM]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'

CREATE Function [dbo].[Convert_Primary_UOM] (@Branch Varchar (12), @Item Decimal(8,0), @PrimaryUOM Char (2), @ConvertUOM Char (2)) Returns Decimal (18,6) As

-- This function is to be used by the RR interface program to display an alternate UOM
-- on the inventory as of view. For each row in the view, the branch plant, item number,
-- primary UOM (UOM colum) and the alternate UOM (drop down) is passed.
-- The function returns a conversion factor as follows:

-- If the primary UOM and Alternate UOM are the same, then the factor = 1.
-- If a conversion factor cannot be determined, the factor = 0.
-- Search for branch level conversion.
-- Search for item level conversion.
-- Search for Standard conversion.

-- The routine returns a decimal value (18,6).

-- The alternate UOM is dervied from a distinct list from vcr_F41003, column UCUM.  


Begin
Declare @Factor Decimal (18,6)

-- Primary and Alternate UOM are the same.

	If @PrimaryUOM = @ConvertUOM
	Begin
	Set @Factor = 1
	GoTo Done
	End

--Branch Level Conversions

	-- Item Primary UOM to Standard
	-- Used when the primary UOM is unique to the item, then converted to standard.
	-- For Example, if the primary is EA''s and the alternate is KG''s.
	-- and there is a EA''s to LB''s in vcr_F41002 
	-- and LB''s to KG conversion in vcr_F41003.

Set @Factor =
	(Select top 1 (UCCONV/UMCONV)
	From vcr_F41002
	Inner Join vcr_F41003 On (UCRUM = UMRUM)
	Where UMMCU = @Branch and UMITM = @ITEM And UMUM = @PrimaryUOM And UCUM = @ConvertUOM)

	If @Factor Is Not Null Begin GoTo Done End 



--Item Level Conversions

	-- Item Primary UOM to Standard
	-- Used when the primary UOM is unique to the item, then converted to standard.
	-- For Example, if the primary is EA''s and the alternate is KG''s.
	-- and there is a EA''s to LB''s in vcr_F41002 
	-- and LB''s to KG conversion in vcr_F41003.

	Set @Factor =
	(Select top 1 (UCCONV/UMCONV)
	From vcr_F41002
	Inner Join vcr_F41003 On (UCRUM = UMRUM)
	Where UMITM = @ITEM And UMUM = @PrimaryUOM And UCUM = @ConvertUOM)

	If @Factor Is Not Null Begin GoTo Done End 
	
	
	
		-- Direct Conversion
	-- Used when the primary UOM is directly converted to standard.
	-- For Example, if the primary is LB''s and the alternate is KG''s.
	-- and there is a LB''s to KG conversion in vcr_F41002.

	Set @Factor =
	(Select (10000000/UMCONV) 
	From vcr_F41002
	Where UMITM = @ITEM And UMUM = @PrimaryUOM And UMRUM = @ConvertUOM)

	If @Factor Is Not Null Begin GoTo Done End 




--Standard UOM Conversions

	-- Direct Conversion
	-- Used when the primary UOM is directly converted to standard.
	-- For Example, if the primary is LB''s and the alternate is KG''s.
	-- and there is a LB''s to KG conversion in vcr_F41003.

	Set @Factor =
	(Select (UCCONV/10000000) 
	From vcr_F41003
	Where UCRUM = @PrimaryUOM And UCUM = @ConvertUOM)

	If @Factor Is Not Null Begin GoTo Done End 



	Set @Factor =
	(Select 10000000/UCCONV
	From vcr_F41003
	Where UCUM = @ConvertUOM And UCRUM = @PrimaryUOM)

	If @Factor Is Not Null Begin GoTo Done End


	-- Double Conversion
	-- Used for double entry conversion in the standards table.
	-- For Example, if the primary is LB''s and the Common is TM''s.
	-- and there is a LB''s to KG''s and KG''s to TM conversion in F41003.

	Set @Factor =
	(Select a.ucconv/10000000 * b.ucconv/10000000
	From vcr_F41003 A
	Inner Join vcr_F41003 B On (a.ucrum = b.ucum)
	Where a.ucum = @PrimaryUOM and b.UCRUM = @ConvertUOM )

	If @Factor Is Not Null Begin GoTo Done End 


-- Conversion factor not found.
	Set @Factor = 0



--Finish
Done:

Return @Factor
end


' 
END

GO
ALTER AUTHORIZATION ON [dbo].[Convert_Primary_UOM] TO  SCHEMA OWNER 
GO
/****** Object:  UserDefinedFunction [dbo].[fn_SplitString]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_SplitString]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'/****** Object:  UserDefinedFunction [dbo].[fn_SplitString]    Script Date: 10/29/2007 17:17:43 ******/
CREATE function [dbo].[fn_SplitString](
 @String nvarchar (4000),
 @Delimiter nvarchar (10) = '',''
 )
returns @ValueTable table (CodeValue nvarchar(4000))
begin
/************************************************************************
Select * from dbo.fn_SplitString(''01212365;00321356;00412582365'','';'')
Select * from dbo.fn_SplitString('''',null)
*************************************************************************/
 declare @NextString nvarchar(4000)
 declare @Pos int
 declare @NextPos int
 declare @CommaCheck nvarchar(1)

 -- return when nothing passed
 if ( @String = '''' or @String is null ) begin
	return 
 end

 --Initialize
 set @NextString = ''''
 set @CommaCheck = right(@String,1) 
 
 --Check for trailing Comma, if not exists, INSERT
 --if (@CommaCheck <> @Delimiter )
 set @String = @String + @Delimiter
 
 --Get position of first Comma
 set @Pos = charindex(@Delimiter,@String)
 set @NextPos = 1
 
 --Loop while there is still a comma in the String of levels
 while (@pos <>  0)  
 begin
  set @NextString = substring(@String,1,@Pos - 1)
 
  insert into @ValueTable (CodeValue) 
         Values (@NextString)
 
  set @String = substring(@String,@pos +1,len(@String))
  
  set @NextPos = @Pos
  set @pos  = charindex(@Delimiter,@String)
 end
 
 return
end
' 
END

GO
ALTER AUTHORIZATION ON [dbo].[fn_SplitString] TO  SCHEMA OWNER 
GO
/****** Object:  UserDefinedFunction [dbo].[ufn_Get_Account]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ufn_Get_Account]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'CREATE function [dbo].[ufn_Get_Account] (@Company Varchar(5), @GLClass Varchar(4),@Branch Varchar(12), @Item Varchar(25),
										 @Order Varchar(2), @Doc Varchar(2), @Qty Float)
Returns VarChar(29)
As 

Begin

Declare @Account Varchar(29)
Set @Account = ''''


-- Outside Operations
If		@Item Like (''%*OP%'')
Begin
Select	@Account = ''Outside Operations''
Goto	Finished
End

-- Account by business unit
-- Check for business unit
Declare @BusinessUnit Varchar(12)
Set		@BusinessUnit = (Select MCMCUS From vcr_F0006 where MCCO = @Company And MCMCU = @Branch)

If		@BusinessUnit <> ''''
Begin

Select	@Account = LongAccount
From	RAAIBase
Where	CompanyNumber = @Company And GLClass = @GLClass And BusinessUnit = @BusinessUnit
If		@Account <> '''' GoTo Finished

End

-- Account by branch plant
Select	@Account = LongAccount
From	RAAIBase
Where	CompanyNumber = @Company And GLClass = @GLClass And BusinessUnit = @Branch
If		@Account <> '''' GoTo Finished


-- Account by GL Class
Select	@Account = LongAccount
From	RAAIBase
Where	CompanyNumber = @Company And GLClass = @GLClass
If		@Account <> '''' GoTo Finished


/*
-- Landed Costs
If		@Doc = ''OV'' And @Qty = 0
Begin
Select	@Account = LongAccount
From	dbo.RAccountInstrEXP
Where	CompanyNumber = @Company AND GLClass = @GLClass AND DocType = @Order And TableNumber = ''4385''
If		@Account <> '''' GoTo Finished
End	
*/

-- Unassigned Account
Select	@Account = ''GL Class not in Base Table''

Finished:

Return @Account
End' 
END

GO
ALTER AUTHORIZATION ON [dbo].[ufn_Get_Account] TO  SCHEMA OWNER 
GO
/****** Object:  UserDefinedFunction [dbo].[ufn_Get_GLClass]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ufn_Get_GLClass]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'CREATE function [dbo].[ufn_Get_GLClass] (@ILMCU Varchar(12), @ILITM Decimal(8,0),@ILLOCN Varchar(20), @ILLOTN Varchar(30))
Returns VarChar(4)
As 

Begin

Declare @GLCLass Varchar(4)
Set @GLClass = ''''


Select	@GLClass = LIGLPT
From	F41021
Where	LIMCU = @ILMCU And LIITM = @ILITM And LILOCN = @ILLOCN And LILOTN = @ILLOTN
If		@GLClass <> '''' GoTo Finished


Select	@GLClass = IBGLPT
From	vcr_F4102
Where	IBMCU = @ILMCU And IBITM = @ILITM
If		@GLClass <> '''' GoTo Finished


Select	@GLClass = IMGLPT
From	vcr_F4101
Where	IMITM = @ILITM


Finished:


Return @GLClass
End' 
END

GO
ALTER AUTHORIZATION ON [dbo].[ufn_Get_GLClass] TO  SCHEMA OWNER 
GO
/****** Object:  UserDefinedFunction [dbo].[ufn_Get_Period_Ends]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ufn_Get_Period_Ends]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'CREATE function [dbo].[ufn_Get_Period_Ends] (@Company Varchar(5), @Date Datetime,@table varchar(5))
Returns SmallDateTime
As 

Begin

Declare @Period DateTime
Set @Period = 0


Select @Period = PeriodEnds
From RPeriodEnds
Where CompanyNumber = @Company And CDate = @Date

If @table = ''T4111''
Begin
	If @Period > (Select MaxPeriodEnds From RCompanies Where CompanyNumber = @Company)
		Begin
		Select @Period = (Select MaxPeriodEnds From RCompanies Where CompanyNumber = @Company)
		End
End



Return @Period
End' 
END

GO
ALTER AUTHORIZATION ON [dbo].[ufn_Get_Period_Ends] TO  SCHEMA OWNER 
GO
/****** Object:  UserDefinedFunction [dbo].[ufn_GetKeyStringValues]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ufn_GetKeyStringValues]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
CREATE function  [dbo].[ufn_GetKeyStringValues] () returns varchar(1000)
as 
BEGIN
    Declare @sCSV varchar(1000)
    -- create empty variable
    set @sCsv = ''''
	-- concatenate version 
	select @sCsv = @sCsv + substring(value,1,2) from RSystemVariables where Name = ''DatabaseVersion''
	-- concatenate expiration date
	select @sCsv = @sCsv + value from RSystemVariables where Name = ''ExpirationDate''
	-- concatenate client number
	select @sCsv = @sCsv + value from RSystemVariables where Name = ''ClientAcctNumber''
	-- concatenate each company number in descending order
    select @sCsv = @sCsv + companyNumber from RCompanies order by companynumber
    -- add the separator and current verification key
    select @sCsv = @sCsv + ''|'' + value from RSystemVariables where Name = ''LicenseKey''
    
    return @sCsv
END
' 
END

GO
ALTER AUTHORIZATION ON [dbo].[ufn_GetKeyStringValues] TO  SCHEMA OWNER 
GO
/****** Object:  UserDefinedFunction [dbo].[ufn_Inv_Analysis]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ufn_Inv_Analysis]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'CREATE function [dbo].[ufn_Inv_Analysis] (@Company Varchar(5), @Account Varchar(29), @Period SmallDateTime,
											@DocType VarChar(2), @DocNumber Decimal(8,0), @OrderType Varchar(2), @Variance Decimal(18,2), @Status Varchar(100))
Returns Varchar(100) As

Begin

Declare @Comment Varchar(100)
Set @Comment = ''''


-- Unbalanced Stock Transfers
If @DocType = ''IT''
Begin

If Exists	(Select * From v_Unbalanced_Stock_Transfers
				Where DocType = @DocType And DocNumber = @DocNumber)
Begin
Select @Comment = ''Unbalanced quantity in stock transfer''
GoTo Finished
End
End


-- Outside Operations in Inventory Account
If Exists (Select * 
			From RCardexLedgerCompare2 A
			Inner Join Outside_Ops B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber)
			Where InventoryAccount <> ''Outside Operations'' And 
			A.CompanyNumber = @Company And A.DocType = @DocType And A.DocNumber = @DocNumber)

Begin
	Select @Comment = ''Outside Operations in Inventory Account''
	GoTo Finished
End 


If @Comment Is Null Begin Select @Comment = '''' End


Finished:
Return @Comment
End' 
END

GO
ALTER AUTHORIZATION ON [dbo].[ufn_Inv_Analysis] TO  SCHEMA OWNER 
GO
/****** Object:  UserDefinedFunction [dbo].[ufn_Mfg_Analysis]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ufn_Mfg_Analysis]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'CREATE function [dbo].[ufn_Mfg_Analysis] (@Company Varchar(5), @Account Varchar(29), @Period SmallDateTime,
										 @DocType VarChar(2), @DocNumber Decimal(8,0), @OrderType Varchar(2), @MfgBatch Decimal(8,0), @Status VarChar(100))
Returns Varchar(100) As

Begin

Declare @Comment Varchar(100)
Set @Comment = ''''


-- Labor or variance in inventory
If @DocType In (''IH'',''IV'') And @Status = ''No Cardex'' Begin Select @Comment = ''Mfg expenses in inventory account'' GoTo Finished End


-- Scrap in inventory
If @DocType = ''IS''  And @Status = ''No GL'' Begin Select @Comment = ''Mfg scrap in cardex'' GoTo Finished End


-- Outside Operations in Inventory Account
If @DocType = ''IM'' And Exists (Select * 
			From RCardexLedgerCompare2 A
			Inner Join Outside_Ops B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber And A.MfgBatch = B.MfgBatch)
			Where InventoryAccount <> ''Outside Operations'' And 
			A.CompanyNumber = @Company And A.DocType = @DocType And A.DocNumber = @DocNumber And A.MfgBatch = @MfgBatch)

Begin
	Select @Comment = ''Outside Operations in Inventory Account''
	GoTo Finished
End 



-- GL entry missing cardex line amount
If @DocType = ''IM'' And @Status = ''Red'' And @Account<> ''Outside Operations'' And
				Exists (Select * From dbo.IM_Missing_GL 
				Where CompanyNumber = @Company And DocType = @DocType And DocNumber = @DocNumber And MfgBatch = @MfgBatch)
Begin
	Select @Comment = ''Work order transaction missing cardex amount in GL''
	GoTo Finished
End 


-- Frozen Cost Variance Level 1
If Exists ( SELECT  ILKCO, ILDCT, ILDOC, ILITM
            FROM    F4111B
			INNER JOIN vcr_F4101     ON ( ILITM = IMITM )
            INNER JOIN RInvCosts A ON ( ILITM = A.ShortItem )
            WHERE  	CostLevel = 1 And ILLITM NOT LIKE ''%*OP%'' AND IMSTKT NOT IN ( ''C'', ''K'' ) And CostMethod = ''07''
					And ILKCO = @Company And ILDCT = @DocType And ILDOC = @DocNumber And ILICU = @MfgBatch And @Status = ''Red'' 
            GROUP BY ILKCO, ILDCT, ILDOC, ILITM
			Having Sum(ILPAID) <> Sum(Cast(FrozenCost * ILTRQT AS DECIMAL(18, 2))))

Begin
Select @Comment = ''Frozen Cost Variance''
GoTo Finished
End


-- Frozen Cost Variance Level 2
If Exists ( SELECT  ILKCO, ILDCT, ILDOC, ILITM
            FROM    F4111B
			INNER JOIN vcr_F4101     ON ( ILITM = IMITM )
			Inner JOIN RInvCosts B ON ( ILITM = B.ShortItem And ILMCU = B.BranchPlant)
            WHERE  	CostLevel = 2 And ILLITM NOT LIKE ''%*OP%'' AND IMSTKT NOT IN ( ''C'', ''K'' ) And CostMethod = ''07''
					And ILKCO = @Company And ILDCT = @DocType And ILDOC = @DocNumber And ILICU = @MfgBatch And @Status = ''Red'' 
            GROUP BY ILKCO, ILDCT, ILDOC, ILITM
			Having Sum(ILPAID) <> Sum(Cast(FrozenCost * ILTRQT AS DECIMAL(18, 2))))

Begin
Select @Comment = ''Frozen Cost Variance''
GoTo Finished
End




-- Frozen Cost Variance Level 3
If Exists ( SELECT  ILKCO, ILDCT, ILDOC, ILITM
            FROM    F4111B
			INNER JOIN vcr_F4101     ON ( ILITM = IMITM )
			Inner JOIN RInvCosts C ON ( ILITM = C.ShortItem And ILMCU = C.BranchPlant And ILLOCN = C.Location And ILLOTN = C.Lot)
            WHERE  	CostLevel = 3 And ILLITM NOT LIKE ''%*OP%'' AND IMSTKT NOT IN ( ''C'', ''K'' ) And CostMethod = ''07''
					And ILKCO = @Company And ILDCT = @DocType And ILDOC = @DocNumber And ILICU = @MfgBatch  And @Status = ''Red'' 
            GROUP BY ILKCO, ILDCT, ILDOC, ILITM
			Having Sum(ILPAID) <> Sum(Cast(FrozenCost * ILTRQT AS DECIMAL(18, 2))))

Begin
Select @Comment = ''Frozen Cost Variance''
GoTo Finished
End


If @Comment Is Null Begin Select @Comment = '''' End


Finished:
Return @Comment
End' 
END

GO
ALTER AUTHORIZATION ON [dbo].[ufn_Mfg_Analysis] TO  SCHEMA OWNER 
GO
/****** Object:  UserDefinedFunction [dbo].[ufn_Purch_Analysis]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ufn_Purch_Analysis]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'CREATE function [dbo].[ufn_Purch_Analysis] (@Company Varchar(5), @Account Varchar(29), @Period SmallDateTime,
											@DocType VarChar(2), @DocNumber Decimal(8,0), @OrderType Varchar(2), 
											@Variance Decimal(18,2), @Status Varchar(100), @MatchDoc Decimal(8,0))
Returns Varchar(100) As

Begin
Declare @Comment Varchar(100), @@Step VARCHAR(30), @@Process VARCHAR(100), @rowc INT
Set @Comment = ''''


-- Direct Shipments
If @OrderType = (Select DirPOType From RConstants)
Begin
Select @Comment = ''Direct Ship Mismatch''
GoTo Finished
End



-- Outside Operation Receipt not in primary location
If @Account = ''Outside Operations'' And @DocType = ''OV''
And Exists (Select *
			From dbo.Out_Ops_Rec A
			Where A.CompanyNumber = @Company And A.Account = @Account And A.PeriodEnds = @Period And 
				  A.DocType = @DocType And A.DocNumber = @DocNumber)
Begin
	Select @Comment = ''Outside Operation receipt not to primary location''
	GoTo Finished
End 


-- Outside Operations Receipt in Inventory Account

If @OrderType = (Select OOPOType From RConstants) And @Account <> ''Outside Operations'' And @DocType = ''OV''
Begin
	Select @Comment = ''Outside Operation receipt in inventory account''
	GoTo Finished
End 



--	Voucher Variance in Account
If @Status = ''No Cardex'' and @DocType <> ''OV''
Begin
Select @Comment = ''Voucher Variance in Account''
GoTo Finished
End




-- Voucher Variance in Cardex
If @Status = ''No GL'' And @DocType <> ''OV''
Begin
Select @Comment = ''Voucher Variance in Cardex''
GoTo Finished
End



-- Landed Costs
If Exists	(Select *
				From v_Landed_Costs
				Where	CompanyNumber = @Company And InventoryAccount = @Account And PeriodEnds = @Period And
						DocType = @DocType And DocNumber = @DocNumber And OrderType = @OrderType)
Begin
Select @Comment = ''Landed Cost''
GoTo Finished
End






-- Zero Balance Adjustments
If Exists	(Select *
				From v_Zero_Balance_Adjustments
				Where	CompanyNumber = @Company And InventoryAccount = @Account And PeriodEnds = @Period And
						DocType = @DocType And DocNumber = @DocNumber And OrderType = @OrderType)
Begin
Select @Comment = ''Zero Balance Adjustment''
GoTo Finished
End





-- Add Cardex Comments
Set @Comment = (Select Top 1 Trex
				From Trex_Pur
				Where	CompanyNumber = @Company And Account = @Account And PeriodEnds = @Period And
						DocType = @DocType And DocNumber = @DocNumber)


If @Comment Is Null Begin Select @Comment = '''' End


Finished:
Return @Comment
End' 
END

GO
ALTER AUTHORIZATION ON [dbo].[ufn_Purch_Analysis] TO  SCHEMA OWNER 
GO
/****** Object:  UserDefinedFunction [dbo].[ufn_Sales_Analysis]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ufn_Sales_Analysis]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'CREATE function [dbo].[ufn_Sales_Analysis] (@Company Varchar(5), @Account Varchar(29), @Period SmallDateTime, 
											@DocType VarChar(2), @DocNumber Decimal(8,0), @OrderType Varchar(2),
											@CXAmount Decimal (18,2))
Returns Varchar(100) As

Begin

Declare @Comment Varchar(100)
Declare @ILKCO VarChar(5),  @ILDCTO VarChar(2), @ILDOCO Decimal(8,0), @ILLNID Numeric(18,3)

Set @Comment = ''''

-- Kit Cost Issue

If Exists	(Select *
				FROM    RCardexLedgerCompare2 A
				Inner Join Kit_Ship B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And
						A.DocNumber = B.DocNumber And A.OrderType = B.OrderType)
				WHERE   A.CardexLedgerVariance + B.Cost = 0 And
						A.CompanyNumber = @Company And A.DocType = @DocType And A.DocNumber = @DocNumber and A.OrderType = @OrderType)


Begin
Select @Comment = ''Kit Item doubled the cost''
GoTo Finished
End




-- Direct Ship Mismatch
If @OrderType = (Select DirSOType From RConstants)
Begin

If Exists (Select *
			From RCardexLedgerCompare2
			Where CompanyNumber = @Company And InventoryAccount = @Account And PeriodEnds = @Period And
					DocType = @DocType And DocNumber = @DocNumber And OrderType = @OrderType)

Begin
Select @Comment = ''Direct Ship Mismatch''
GoTo Finished
End
End




-- Multiple Shipments in Cardex
If Exists (Select *
			From Mult_Ship
			Where CompanyNumber = @Company And DocType = @DocType And DocNumber = @DocNumber And OrderType = @OrderType)


Begin
Select @Comment = ''Multiple Shipments in Cardex''
GoTo Finished
End



-- Missing Cardex Entries

If Exists	(Select *
				From	Missing_Cardex
				Where	CompanyNumber = @Company And DocType = @DocType And DocNumber = @DocNumber And OrderType = @OrderType)

Begin
Select @Comment = ''Cardex missing sales line''
GoTo Finished
End


-- Non Stock Lines

If Exists	(Select *
			 From Line_Types A
			 Where	A.CompanyNumber = @Company And A.DocType = @DocType And A.DocNumber = @DocNumber And A.OrderType = @OrderType)

Begin
Select @Comment = ''Line Type '' + LineType + '' GL Class '' + GLClass
				From RCardexLedgerCompare2 A
				Inner Join	Line_Types B On (A.CompanyNumber = B.CompanyNumber And A.DocType = B.DocType And A.DocNumber = B.DocNumber And A.OrderType = B.OrderType)
				Where	A.CompanyNumber = @Company And A.DocType = @DocType And A.DocNumber = @DocNumber And A.OrderType = @OrderType
						And Status = ''No Cardex''

GoTo Finished
End


	
-- Cost/Quantity Changes
    DECLARE C1 CURSOR FOR 
			Select	Distinct ILKCO, ILDCTO, ILDOCO, ILLNID
			From	F4111B
			Where	ILKCO = @Company And ILDCT = @DocType And ILDOC = @DocNumber And ILDCTO = @OrderType
			Group By ILKCO, ILDCTO, ILDOCO, ILLNID
			Having Count(*) = 1 
			Order By ILLNID

    OPEN C1
    FETCH NEXT FROM C1 INTO @ILKCO, @ILDCTO, @ILDOCO, @ILLNID
    WHILE 		@@FETCH_STATUS = 0
    BEGIN


SET  @Comment = ( Select Top 1
        CASE WHEN ILUNCS <> SDUNCS And SDKCOO = SDCO THEN ''Cardex/Sales cost variance '' + CAST(ILDOCO AS VARCHAR) + '' '' + ILDCTO + '' '' + CAST(ILLNID AS VARCHAR)
             WHEN ILUNCS <> SDTCST And SDKCOO <> SDCO THEN ''Interco Cardex/Sales variance '' + CAST(ILDOCO AS VARCHAR) + '' '' + ILDCTO + '' '' + CAST(ILLNID AS VARCHAR)
  			 WHEN ILTRQT +  SDPQOR <> 0 THEN ''Qty changed after ship confirm '' + CAST(ILDOCO AS VARCHAR) + '' '' + ILDCTO + '' '' + CAST(ILLNID AS VARCHAR)
			 WHEN SDTCST = 0 AND SDSO01 = ''1'' THEN ''Transfer Cost $0 - I/B Doc JE '' + RTRIM(CONVERT(CHAR, ILDOC)) + '' '' + SDDCTO + '' '' + RTRIM(CONVERT(CHAR, SDDOCO))
			 WHEN SDCSTO = ''1'' THEN ''Cost Override Flag Set''
             ELSE '''' END
            FROM    F4111B A
            INNER JOIN F42119 B ON SDKCOO = ILKCOO AND SDCO = ILKCO AND SDDOCO = ILDOCO AND SDDCTO = ILDCTO AND SDLNID = ILLNID and A.PeriodEnds = B.PeriodEnds
			Where ILKCO = @ILKCO And ILDCTO = @ILDCTO And ILDOCO = @ILDOCO And ILLNID = @ILLNID And ILLITM = SDLITM)

			If @Comment = '''' FETCH NEXT FROM C1 INTO @ILKCO, @ILDCTO, @ILDOCO, @ILLNID Else GoTo Close_Cur
    END

Close_Cur:
    CLOSE C1
    DEALLOCATE C1


-- Add Cardex Comments

If @Comment = ''''
Begin
Set @Comment = (Select Top 1 Trex
				From Trex_Sales
				Where	CompanyNumber = @Company And Account = @Account And PeriodEnds = @Period And
						DocType = @DocType And DocNumber = @DocNumber)
End


If @Comment Is Null Begin Select @Comment = '''' End



Finished:
Return @Comment
End' 
END

GO
ALTER AUTHORIZATION ON [dbo].[ufn_Sales_Analysis] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[Branches]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Branches]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Branches](
	[BranchPlant] [nvarchar](12) NULL,
	[ShortItem] [decimal](8, 0) NULL,
	[ItemNumber] [nvarchar](25) NULL,
	[RawQOH] [decimal](18, 2) NULL,
	[PerpQOH] [decimal](18, 2) NULL,
	[Diff] [decimal](18, 2) NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
ALTER AUTHORIZATION ON [dbo].[Branches] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[CXAccounts]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CXAccounts]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[CXAccounts](
	[Account] [nvarchar](29) NULL,
	[SummaryAmount] [decimal](18, 2) NULL,
	[DetailAmount] [decimal](18, 2) NULL,
	[Diff] [decimal](18, 2) NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
ALTER AUTHORIZATION ON [dbo].[CXAccounts] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[Dates]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Dates]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Dates](
	[Dates] [datetime] NOT NULL,
	[CalendarYear] [char](4) NOT NULL,
	[CalendarQuarter] [char](1) NOT NULL,
	[CalendarMonth] [char](2) NOT NULL,
	[CalendarMonthName] [char](10) NOT NULL,
	[CalendarMonthNameShort] [char](3) NOT NULL,
	[CalendarWeek] [char](2) NOT NULL,
	[CalendarDateWeekBegins] [datetime] NOT NULL,
	[CalendarJulian] [int] NOT NULL,
	[Counter] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_Dates] PRIMARY KEY CLUSTERED 
(
	[CalendarJulian] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[Dates] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[EXPConversions]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EXPConversions]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[EXPConversions](
	[ConverterBranchPlant] [varchar](12) NOT NULL,
	[ConverterShortItem] [decimal](8, 0) NOT NULL,
	[ConverterUOM] [char](2) NOT NULL,
	[ConverterCommonUOM] [char](2) NOT NULL,
	[ConversionFactor] [decimal](18, 6) NULL,
PRIMARY KEY CLUSTERED 
(
	[ConverterBranchPlant] ASC,
	[ConverterShortItem] ASC,
	[ConverterUOM] ASC,
	[ConverterCommonUOM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[EXPConversions] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[F0010]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F0010]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[F0010](
	[CCCO] [varchar](5) NOT NULL,
	[CCNAME] [varchar](30) NOT NULL,
	[CCDTPN] [varchar](1) NOT NULL,
	[CCDFYJ] [datetime] NOT NULL,
	[CCPNC] [decimal](9, 0) NOT NULL,
 CONSTRAINT [PK_F0010] PRIMARY KEY CLUSTERED 
(
	[CCCO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[F0010] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[F0902]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F0902]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[F0902](
	[GBAID] [varchar](50) NOT NULL,
	[GBFY] [decimal](2, 0) NOT NULL,
	[GBLT] [varchar](2) NOT NULL,
	[GBCO] [varchar](5) NOT NULL,
	[GBAPYC] [decimal](17, 2) NOT NULL,
	[GBAN01] [decimal](17, 2) NOT NULL,
	[GBAN02] [decimal](17, 2) NOT NULL,
	[GBAN03] [decimal](17, 2) NOT NULL,
	[GBAN04] [decimal](17, 2) NOT NULL,
	[GBAN05] [decimal](17, 2) NOT NULL,
	[GBAN06] [decimal](17, 2) NOT NULL,
	[GBAN07] [decimal](17, 2) NOT NULL,
	[GBAN08] [decimal](17, 2) NOT NULL,
	[GBAN09] [decimal](17, 2) NOT NULL,
	[GBAN10] [decimal](17, 2) NOT NULL,
	[GBAN11] [decimal](17, 2) NOT NULL,
	[GBAN12] [decimal](17, 2) NOT NULL,
	[GBAN13] [decimal](17, 2) NOT NULL,
	[GBAN14] [decimal](17, 2) NOT NULL,
 CONSTRAINT [PK_F0902] PRIMARY KEY CLUSTERED 
(
	[GBAID] ASC,
	[GBFY] ASC,
	[GBLT] ASC,
	[GBCO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[F0902] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[F0911]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F0911]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[F0911](
	[GLKCO] [varchar](5) NOT NULL,
	[GLCO] [varchar](5) NOT NULL,
	[GLDCT] [varchar](2) NOT NULL,
	[GLDOC] [decimal](8, 0) NOT NULL,
	[GLDCTO] [varchar](2) NOT NULL,
	[GLPDCT] [varchar](2) NOT NULL,
	[GLFY] [decimal](2, 0) NOT NULL,
	[GLPN] [decimal](2, 0) NOT NULL,
	[GLPOST] [varchar](1) NOT NULL,
	[GLICU] [decimal](8, 0) NOT NULL,
	[GLICUT] [varchar](2) NOT NULL,
	[GLAID] [varchar](8) NOT NULL,
	[GLMCU] [varchar](12) NOT NULL,
	[GLOBJ] [varchar](6) NOT NULL,
	[GLSUB] [varchar](8) NOT NULL,
	[GLDGJ] [datetime] NOT NULL,
	[GLAA] [float] NOT NULL,
	[GLUSER] [varchar](10) NOT NULL,
	[GLSBL] [varchar](8) NOT NULL,
	[GLANI] [varchar](29) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[GLPO] [varchar](8) NOT NULL,
	[GLLNID] [numeric](18, 3) NOT NULL,
	[GLR1] [varchar](8) NOT NULL,
	[GLR2] [varchar](8) NOT NULL,
	[Formatted] [tinyint] NOT NULL,
	[Prepped] [tinyint] NOT NULL,
	[Keyed] [tinyint] NOT NULL,
	[GLDICJ] [datetime] NOT NULL,
	[GLKey] [datetime] NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[F0911] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[F3106]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F3106]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[F3106](
	[SDDOCO] [float] NOT NULL,
	[SDDOC] [float] NOT NULL,
	[SDDCT] [nchar](2) NOT NULL,
	[SDDGJ] [datetime] NOT NULL,
	[SDICU] [float] NOT NULL,
	[SDICUT] [nchar](2) NOT NULL,
	[SDDICJ] [datetime] NOT NULL,
	[SDJOBN] [nchar](10) NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
ALTER AUTHORIZATION ON [dbo].[F3106] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[F3112]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F3112]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[F3112](
	[WLDOCO] [decimal](8, 0) NOT NULL,
	[WLDCTO] [char](2) NOT NULL,
	[WLMMCU] [char](12) NOT NULL,
	[WLVEND] [decimal](8, 0) NOT NULL,
	[WLRKCO] [char](5) NOT NULL,
	[WLRORN] [char](8) NOT NULL,
	[WLRCTO] [char](2) NOT NULL,
	[WLRLLN] [numeric](18, 0) NOT NULL,
	[WLUPMJ] [datetime] NOT NULL,
	[WLKITL] [varchar](25) NOT NULL,
	[WLOPSQ] [decimal](9, 0) NOT NULL,
	[Formatted] [tinyint] NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[F3112] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[F4095_WT]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F4095_WT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[F4095_WT](
	[MLCO] [varchar](5) NOT NULL,
	[MLANUM] [decimal](4, 0) NOT NULL,
	[MLDCTO] [varchar](2) NOT NULL,
	[MLDCT] [varchar](2) NOT NULL,
	[MLGLPT] [varchar](4) NOT NULL,
	[MLMCU] [varchar](12) NOT NULL,
	[MLOBJ] [varchar](6) NOT NULL,
	[MLSUB] [varchar](8) NULL,
	[MLCOST] [varchar](3) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[F4095_WT] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[F41021]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F41021]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[F41021](
	[LIITM] [decimal](8, 0) NOT NULL,
	[LIMCU] [varchar](12) NOT NULL,
	[LILOCN] [varchar](20) NOT NULL,
	[LILOTN] [varchar](30) NOT NULL,
	[LIPBIN] [varchar](1) NOT NULL,
	[LIGLPT] [varchar](4) NOT NULL,
	[LILOTS] [varchar](1) NOT NULL,
	[LILRCJ] [datetime] NOT NULL,
	[LIPQOH] [float] NOT NULL,
	[LIUPMJ] [datetime] NOT NULL,
	[LITDAY] [float] NOT NULL,
	[LIKEY] [datetime] NOT NULL,
 CONSTRAINT [PK_F41021] PRIMARY KEY CLUSTERED 
(
	[LIITM] ASC,
	[LIMCU] ASC,
	[LILOCN] ASC,
	[LILOTN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[F41021] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[F4105]    Script Date: 5/8/13 12:13:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F4105]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[F4105](
	[COITM] [decimal](8, 0) NOT NULL,
	[COMCU] [varchar](12) NOT NULL,
	[COLOCN] [varchar](20) NOT NULL,
	[COLOTN] [varchar](30) NOT NULL,
	[COLEDG] [varchar](2) NOT NULL,
	[COUNCS] [float] NULL,
	[COUPMJ] [datetime] NOT NULL,
	[Formatted] [tinyint] NOT NULL,
 CONSTRAINT [PK_F4105] PRIMARY KEY CLUSTERED 
(
	[COITM] ASC,
	[COMCU] ASC,
	[COLOCN] ASC,
	[COLOTN] ASC,
	[COLEDG] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[F4105] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[F4111B]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F4111B]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[F4111B](
	[ILKCOO] [varchar](5) NOT NULL,
	[ILKCO] [varchar](5) NOT NULL,
	[ILDCT] [varchar](2) NOT NULL,
	[ILDOC] [decimal](8, 0) NOT NULL,
	[ILDCTO] [varchar](2) NOT NULL,
	[ILMCU] [varchar](12) NOT NULL,
	[ILLITM] [varchar](25) NOT NULL,
	[ILLOCN] [varchar](20) NOT NULL,
	[ILLOTN] [varchar](30) NOT NULL,
	[ILGLPT] [varchar](4) NOT NULL,
	[ILDGL] [datetime] NOT NULL,
	[ILTRDJ] [datetime] NOT NULL,
	[ILPAID] [float] NOT NULL,
	[ILICU] [decimal](9, 0) NOT NULL,
	[InsertedinCXGL] [int] NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[InventoryAccount] [varchar](29) NOT NULL,
	[ILDOCO] [decimal](9, 0) NOT NULL,
	[ILLNID] [numeric](18, 3) NOT NULL,
	[ILCRDJ] [datetime] NOT NULL,
	[ILTDAY] [decimal](9, 0) NOT NULL,
	[ILIPCD] [varchar](1) NOT NULL,
	[Repaired] [varchar](30) NOT NULL,
	[ILTREF] [varchar](8) NOT NULL,
	[ILUKID] [decimal](18, 0) NOT NULL,
	[RCode] [varchar](30) NOT NULL,
	[OldGLClass] [varchar](4) NOT NULL,
	[Formatted] [tinyint] NOT NULL,
	[RepFlag] [tinyint] NOT NULL,
	[Prepped] [tinyint] NOT NULL,
	[CXKey] [datetime] NOT NULL,
	[ILTREX] [varchar](30) NOT NULL,
	[ILUNCS] [float] NOT NULL,
	[ILTRUM] [char](2) NOT NULL,
	[ILTRQT] [float] NOT NULL,
	[PrimeFlag] [char](2) NOT NULL,
	[ILITM] [decimal](8, 0) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[F4111B] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[F4211]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F4211]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[F4211](
	[SDKCOO] [varchar](5) NOT NULL,
	[SDDOCO] [decimal](8, 0) NOT NULL,
	[SDDCTO] [varchar](2) NOT NULL,
	[SDLNID] [numeric](18, 3) NOT NULL,
	[SDLITM] [varchar](25) NOT NULL,
	[SDUNCS] [decimal](18, 6) NOT NULL,
	[SDECST] [decimal](18, 2) NOT NULL,
	[SDTCST] [decimal](18, 6) NOT NULL,
	[SDUPRC] [float] NOT NULL,
	[SDDOC] [decimal](8, 0) NOT NULL,
	[SDDCT] [varchar](2) NOT NULL,
	[SDMCU] [varchar](12) NOT NULL,
	[SDCO] [varchar](5) NOT NULL,
	[SDDGL] [datetime] NOT NULL,
	[SDGLC] [varchar](4) NOT NULL,
	[SDLNTY] [varchar](2) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[SDCSTO] [varchar](1) NOT NULL,
	[SDSO01] [varchar](1) NOT NULL,
	[SDSO02] [varchar](1) NOT NULL,
	[SDLOCN] [varchar](20) NOT NULL,
	[SDLOTN] [varchar](30) NOT NULL,
	[SDRORN] [varchar](8) NOT NULL,
	[SDRCTO] [varchar](8) NOT NULL,
	[SDRLLN] [numeric](18, 3) NOT NULL,
	[SDTRDJ] [datetime] NOT NULL,
	[SDPQOR] [decimal](18, 2) NOT NULL,
	[SDAN8] [decimal](8, 0) NOT NULL,
	[SDSHAN] [decimal](8, 0) NOT NULL,
	[Formatted] [tinyint] NOT NULL,
	[SDLTTR] [varchar](3) NOT NULL,
	[SDNXTR] [varchar](3) NOT NULL,
	[SDUOM1] [varchar](2) NOT NULL,
	[SDAEXP] [decimal](18, 2) NOT NULL,
	[SDSOQS] [decimal](18, 2) NOT NULL,
	[SDUOM] [varchar](2) NOT NULL,
	[SDSOBK] [decimal](18, 2) NOT NULL,
	[SDOKC] [varchar](5) NULL,
	[SDODOC] [float] NULL,
	[SDODCT] [varchar](2) NULL,
	[SDOORN] [varchar](8) NULL,
	[SDOCTO] [varchar](2) NULL,
	[SDOKCO] [varchar](5) NULL,
	[SDOGNO] [numeric](18, 3) NULL,
	[SDRKCO] [varchar](5) NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[F4211] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[F42119]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F42119]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[F42119](
	[SDKCOO] [varchar](5) NOT NULL,
	[SDDOCO] [decimal](8, 0) NOT NULL,
	[SDDCTO] [varchar](2) NOT NULL,
	[SDLNID] [numeric](18, 3) NOT NULL,
	[SDLITM] [varchar](25) NOT NULL,
	[SDUNCS] [decimal](18, 6) NOT NULL,
	[SDECST] [decimal](18, 2) NOT NULL,
	[SDTCST] [decimal](18, 6) NOT NULL,
	[SDDOC] [decimal](8, 0) NOT NULL,
	[SDDCT] [varchar](2) NOT NULL,
	[SDMCU] [varchar](12) NOT NULL,
	[SDCO] [varchar](5) NOT NULL,
	[SDDGL] [datetime] NOT NULL,
	[SDGLC] [varchar](4) NOT NULL,
	[SDLNTY] [varchar](2) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[SDCSTO] [varchar](1) NOT NULL,
	[SDSO01] [varchar](1) NOT NULL,
	[SDSO02] [varchar](1) NOT NULL,
	[SDLOCN] [varchar](20) NOT NULL,
	[SDLOTN] [varchar](30) NOT NULL,
	[SDRORN] [varchar](8) NOT NULL,
	[SDRCTO] [varchar](2) NOT NULL,
	[SDRLLN] [decimal](18, 3) NOT NULL,
	[SDPQOR] [decimal](18, 4) NOT NULL,
	[SDUPRC] [float] NOT NULL,
	[SDAN8] [decimal](8, 0) NOT NULL,
	[SDSHAN] [decimal](8, 0) NOT NULL,
	[Formatted] [tinyint] NOT NULL,
	[SDUPMJ] [datetime] NOT NULL,
	[SDTDAY] [decimal](9, 0) NOT NULL,
	[SDKEY] [datetime] NOT NULL,
	[SDNXTR] [varchar](3) NOT NULL,
	[SDLTTR] [varchar](3) NOT NULL,
	[SDUOM1] [varchar](2) NOT NULL,
	[SDAEXP] [decimal](18, 2) NOT NULL,
	[SDSOQS] [decimal](18, 2) NOT NULL,
	[SDUOM] [varchar](2) NOT NULL,
	[SDSOBK] [decimal](18, 2) NOT NULL,
	[SDOKC] [varchar](5) NULL,
	[SDODOC] [float] NULL,
	[SDODCT] [varchar](2) NULL,
	[SDOORN] [varchar](8) NULL,
	[SDOCTO] [varchar](2) NULL,
	[SDOKCO] [varchar](5) NULL,
	[SDOGNO] [numeric](18, 3) NULL,
	[SDRKCO] [varchar](5) NULL,
 CONSTRAINT [PK_F42119] PRIMARY KEY CLUSTERED 
(
	[SDKCOO] ASC,
	[SDDOCO] ASC,
	[SDDCTO] ASC,
	[SDLNID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[F42119] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[F4311]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F4311]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[F4311](
	[PDKCOO] [varchar](5) NOT NULL,
	[PDDOCO] [decimal](8, 0) NOT NULL,
	[PDDCTO] [varchar](2) NOT NULL,
	[PDSFXO] [nchar](3) NULL,
	[PDLNID] [numeric](18, 3) NOT NULL,
	[PDLITM] [varchar](25) NOT NULL,
	[PDPRRC] [float] NOT NULL,
	[PDAEXP] [float] NOT NULL,
	[PDMCU] [varchar](12) NOT NULL,
	[PDCO] [varchar](5) NOT NULL,
	[PDDGL] [datetime] NOT NULL,
	[PDGLC] [varchar](4) NOT NULL,
	[PDLNTY] [varchar](2) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[PDLOCN] [varchar](20) NOT NULL,
	[PDLOTN] [varchar](30) NOT NULL,
	[PDRORN] [varchar](8) NOT NULL,
	[PDRCTO] [varchar](8) NOT NULL,
	[PDRLLN] [numeric](18, 3) NOT NULL,
	[PDTRDJ] [datetime] NOT NULL,
	[PDPQOR] [float] NOT NULL,
	[PDAN8] [decimal](8, 0) NOT NULL,
	[PDSHAN] [decimal](8, 0) NOT NULL,
	[PDAOPN] [decimal](18, 2) NOT NULL,
	[PDAREC] [decimal](18, 2) NOT NULL,
	[Formatted] [tinyint] NOT NULL,
	[PDUOPN] [float] NOT NULL,
	[PDUREC] [decimal](18, 4) NOT NULL,
	[PDKEY] [datetime] NOT NULL,
	[PDLTTR] [varchar](3) NOT NULL,
	[PDNXTR] [varchar](3) NOT NULL,
	[PDUOM] [varchar](2) NOT NULL,
	[PDRKCO] [varchar](5) NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[F4311] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[IM_Missing_GL]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[IM_Missing_GL]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[IM_Missing_GL](
	[CompanyNumber] [varchar](5) NULL,
	[Account] [varchar](29) NULL,
	[PeriodEnds] [smalldatetime] NULL,
	[DocType] [varchar](2) NULL,
	[DocNumber] [decimal](8, 0) NULL,
	[MfgBatch] [decimal](8, 0) NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[IM_Missing_GL] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[Item_Roll_Forward]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Item_Roll_Forward]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Item_Roll_Forward](
	[BranchPlant] [varchar](12) NOT NULL,
	[ItemNumber] [varchar](25) NOT NULL,
	[Location] [varchar](30) NOT NULL,
	[Lot] [varchar](30) NOT NULL,
	[Comment] [varchar](25) NOT NULL,
	[DocType] [varchar](2) NOT NULL,
	[DocNumber] [decimal](8, 0) NOT NULL,
	[Quantity] [decimal](18, 4) NOT NULL,
	[UOM] [char](2) NOT NULL,
	[Amount] [decimal](18, 2) NOT NULL,
	[DateTime1] [varchar](25) NOT NULL,
	[CXKey] [decimal](18, 6) NOT NULL,
	[TransTime] [smalldatetime] NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[Item_Roll_Forward] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[R0911NonInv]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[R0911NonInv]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[R0911NonInv](
	[GLKCO] [varchar](5) NOT NULL,
	[GLCO] [varchar](5) NOT NULL,
	[GLDCT] [varchar](2) NOT NULL,
	[GLDOC] [decimal](8, 0) NOT NULL,
	[GLDCTO] [varchar](2) NOT NULL,
	[GLPDCT] [varchar](2) NOT NULL,
	[GLFY] [decimal](2, 0) NOT NULL,
	[GLPN] [decimal](2, 0) NOT NULL,
	[GLPOST] [varchar](1) NOT NULL,
	[GLICU] [decimal](8, 0) NOT NULL,
	[GLICUT] [varchar](2) NOT NULL,
	[GLAID] [varchar](8) NOT NULL,
	[GLMCU] [varchar](12) NOT NULL,
	[GLOBJ] [varchar](6) NOT NULL,
	[GLSUB] [varchar](8) NOT NULL,
	[GLDGJ] [datetime] NOT NULL,
	[GLAA] [decimal](18, 2) NOT NULL,
	[GLUSER] [varchar](10) NOT NULL,
	[GLSBL] [varchar](8) NOT NULL,
	[GLANI] [varchar](29) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[GLPO] [varchar](8) NOT NULL,
	[GLLNID] [numeric](18, 3) NOT NULL,
	[GLR1] [varchar](8) NOT NULL,
	[GLR2] [varchar](8) NOT NULL,
	[Formatted] [tinyint] NOT NULL,
	[Prepped] [tinyint] NOT NULL,
	[Keyed] [tinyint] NOT NULL,
	[GLDICJ] [datetime] NOT NULL,
	[GLKey] [decimal](18, 6) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[R0911NonInv] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RAAIBase]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RAAIBase]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RAAIBase](
	[CompanyNumber] [varchar](5) NOT NULL,
	[GLClass] [varchar](4) NOT NULL,
	[BusinessUnit] [varchar](12) NOT NULL,
	[LongAccount] [varchar](29) NOT NULL,
 CONSTRAINT [PK_RAAIBase] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC,
	[GLClass] ASC,
	[BusinessUnit] ASC,
	[LongAccount] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RAAIBase] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RAAIDiscr]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RAAIDiscr]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RAAIDiscr](
	[CompanyNumber] [varchar](5) NOT NULL,
	[TableNumber] [decimal](9, 0) NOT NULL,
	[GLClass] [varchar](4) NOT NULL,
	[DocType] [varchar](2) NOT NULL,
	[BaseAccount] [varchar](29) NOT NULL,
	[CurrentAccount] [varchar](29) NOT NULL,
	[Comment] [varchar](50) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RAAIDiscr] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RAccountInstr]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RAccountInstr]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RAccountInstr](
	[TableNumber] [decimal](4, 0) NOT NULL,
	[CompanyNumber] [varchar](5) NOT NULL,
	[OrderType] [varchar](2) NOT NULL,
	[DocType] [varchar](2) NOT NULL,
	[GLClass] [varchar](4) NOT NULL,
	[BusinessUnit] [varchar](12) NOT NULL,
	[ObjectAccount] [varchar](6) NOT NULL,
	[SubAccount] [varchar](8) NOT NULL,
	[LongAccount] [varchar](29) NOT NULL,
	[WildCardGL] [varchar](1) NOT NULL,
	[Comment] [varchar](50) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RAccountInstr] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RAccountInstr_WT]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RAccountInstr_WT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RAccountInstr_WT](
	[TableNumber] [decimal](4, 0) NOT NULL,
	[CompanyNumber] [varchar](5) NOT NULL,
	[OrderType] [varchar](2) NOT NULL,
	[DocType] [varchar](2) NOT NULL,
	[GLClass] [varchar](4) NOT NULL,
	[BusinessUnit] [varchar](12) NOT NULL,
	[WildCardGL] [varchar](1) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RAccountInstr_WT] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RAccountInstrEXP]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RAccountInstrEXP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RAccountInstrEXP](
	[TableNumber] [decimal](4, 0) NOT NULL,
	[CompanyNumber] [varchar](5) NOT NULL,
	[OrderType] [varchar](2) NOT NULL,
	[DocType] [varchar](2) NOT NULL,
	[GLClass] [varchar](4) NOT NULL,
	[BusinessUnit] [varchar](12) NOT NULL,
	[ObjectAccount] [varchar](6) NOT NULL,
	[SubAccount] [varchar](8) NOT NULL,
	[LongAccount] [varchar](29) NULL,
	[WildCardGL] [varchar](1) NOT NULL,
	[Comment] [varchar](50) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RAccountInstrEXP] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RAvgCostUpdate]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RAvgCostUpdate]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RAvgCostUpdate](
	[UKID] [decimal](18, 0) NOT NULL,
	[ShortItem] [decimal](8, 0) NOT NULL,
	[BranchPlant] [nvarchar](12) NOT NULL,
	[ItemNumber] [nvarchar](25) NOT NULL,
	[Location] [nvarchar](20) NOT NULL,
	[Lot] [nvarchar](30) NOT NULL,
	[CompanyNumber] [nvarchar](5) NULL,
	[AsOf] [nvarchar](25) NULL,
	[PeriodEnds] [smalldatetime] NULL,
	[TransDate] [smalldatetime] NULL,
	[DocType] [nvarchar](2) NULL,
	[DocNumber] [decimal](8, 0) NULL,
	[Quantity] [float] NULL,
	[UnitCost] [float] NULL,
	[ExtCost] [float] NULL,
	[PrevBal] [float] NULL,
	[RunBal] [float] NULL,
	[PrevAvg] [float] NULL,
	[QOH] [float] NULL,
	[CalcAvg] [float] NULL,
	[CurrCost] [float] NULL,
	[NewExtCost] [float] NULL,
	[CostLevel] [nvarchar](1) NULL,
	[Flag] [tinyint] NULL,
	[Reval] [float] NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
ALTER AUTHORIZATION ON [dbo].[RAvgCostUpdate] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RBaseline]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBaseline]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBaseline](
	[CompanyNumber] [varchar](5) NOT NULL,
	[LongAccount] [varchar](29) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[EndingGLBalance] [float] NOT NULL,
	[SumCardex] [float] NOT NULL,
	[SumPerpetual] [float] NOT NULL,
	[BaselineAOH] [float] NOT NULL,
	[BaselineVar] [float] NOT NULL,
	[CaptureDate] [varchar](25) NOT NULL,
	[Cutoff] [datetime] NOT NULL,
 CONSTRAINT [PK_RBaseline] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC,
	[LongAccount] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RBaseline] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RBaselinePerpetual]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBaselinePerpetual]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBaselinePerpetual](
	[CompanyNumber] [varchar](5) NOT NULL,
	[LongAccount] [varchar](29) NOT NULL,
	[BranchPlant] [varchar](12) NOT NULL,
	[ShortItem] [decimal](8, 0) NOT NULL,
	[ItemNumber] [varchar](25) NOT NULL,
	[Location] [varchar](20) NOT NULL,
	[Lot] [varchar](30) NOT NULL,
	[AmountOnHand] [float] NOT NULL,
	[AmountInCardex] [float] NOT NULL,
	[QuantityonHand] [float] NOT NULL,
	[QuantityinCardex] [float] NOT NULL,
	[PrimaryUOM] [char](2) NOT NULL,
	[LastUpdate] [decimal](18, 6) NOT NULL,
	[CardexUpdate] [decimal](18, 6) NOT NULL,
	[DocType] [varchar](2) NOT NULL,
	[DocNumber] [decimal](8, 0) NOT NULL,
	[DocAmount] [decimal](18, 2) NOT NULL,
	[BL] [tinyint] NOT NULL,
 CONSTRAINT [PK_RBaselinePerpetual_1] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC,
	[LongAccount] ASC,
	[BranchPlant] ASC,
	[ShortItem] ASC,
	[Location] ASC,
	[Lot] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RBaselinePerpetual] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RBegGLBalances]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBegGLBalances]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBegGLBalances](
	[CompanyNumber] [varchar](5) NOT NULL,
	[LongAccount] [varchar](28) NOT NULL,
	[PeriodBegins] [datetime] NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[BeginningBalance] [float] NOT NULL,
 CONSTRAINT [PK_RBegGLBalances] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC,
	[LongAccount] ASC,
	[PeriodEnds] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RBegGLBalances] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RCardexLedgerCompare]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RCardexLedgerCompare]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RCardexLedgerCompare](
	[CompanyNumber] [varchar](5) NOT NULL,
	[InventoryAccount] [varchar](29) NOT NULL,
	[Status] [varchar](100) NOT NULL,
	[OrderType] [varchar](6) NOT NULL,
	[DocType] [varchar](2) NOT NULL,
	[DocNumber] [decimal](8, 0) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[MfgBatch] [decimal](8, 0) NOT NULL,
	[CardexAmount] [float] NOT NULL,
	[LedgerAmount] [float] NOT NULL,
	[CardexLedgerVariance] [float] NOT NULL,
	[MatchingDocument] [decimal](9, 0) NOT NULL,
	[MatchingType] [varchar](2) NOT NULL,
	[Comment] [varchar](100) NOT NULL,
	[TransDate] [datetime] NOT NULL,
 CONSTRAINT [pk_RCardexLedgerCompare] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC,
	[InventoryAccount] ASC,
	[PeriodEnds] ASC,
	[DocType] ASC,
	[DocNumber] ASC,
	[OrderType] ASC,
	[MfgBatch] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RCardexLedgerCompare] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RCardexLedgerCompare2]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RCardexLedgerCompare2]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RCardexLedgerCompare2](
	[CompanyNumber] [varchar](5) NOT NULL,
	[InventoryAccount] [varchar](29) NOT NULL,
	[Status] [varchar](100) NOT NULL,
	[OrderType] [varchar](6) NOT NULL,
	[DocType] [varchar](2) NOT NULL,
	[DocNumber] [decimal](8, 0) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[MfgBatch] [decimal](8, 0) NOT NULL,
	[CardexAmount] [decimal](18, 2) NOT NULL,
	[LedgerAmount] [decimal](18, 2) NOT NULL,
	[CardexLedgerVariance] [decimal](18, 2) NOT NULL,
	[MatchingDocument] [decimal](9, 0) NOT NULL,
	[MatchingType] [varchar](2) NOT NULL,
	[Comment] [varchar](100) NOT NULL,
	[TransDate] [datetime] NOT NULL,
 CONSTRAINT [pk_RCardexLedgerCompare2] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC,
	[InventoryAccount] ASC,
	[PeriodEnds] ASC,
	[DocType] ASC,
	[DocNumber] ASC,
	[OrderType] ASC,
	[MfgBatch] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RCardexLedgerCompare2] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RCardexLedgerCompare2WorkNote]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RCardexLedgerCompare2WorkNote]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RCardexLedgerCompare2WorkNote](
	[CompanyNumber] [varchar](5) NOT NULL,
	[InventoryAccount] [varchar](29) NOT NULL,
	[OrderType] [varchar](6) NOT NULL,
	[DocType] [varchar](2) NOT NULL,
	[DocNumber] [decimal](8, 0) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[MfgBatch] [decimal](8, 0) NOT NULL,
	[Worked] [bit] NOT NULL,
	[Note] [varchar](5000) NULL,
	[LastModifiedBy] [varchar](50) NOT NULL,
	[LastModifiedDate] [datetime] NOT NULL,
 CONSTRAINT [pk_RCardexLedgerCompare2WorkNote] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC,
	[InventoryAccount] ASC,
	[PeriodEnds] ASC,
	[DocType] ASC,
	[DocNumber] ASC,
	[OrderType] ASC,
	[MfgBatch] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RCardexLedgerCompare2WorkNote] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RCompanies]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RCompanies]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RCompanies](
	[CompanyNumber] [varchar](5) NOT NULL,
	[PeriodCutoff] [datetime] NOT NULL,
	[SubLedgerWO] [int] NOT NULL,
	[CutoffJulian] [decimal](6, 0) NOT NULL,
	[BaselineExist] [tinyint] NOT NULL,
	[MaxPeriodEnds] [datetime] NOT NULL,
	[FiscalYear] [int] NOT NULL,
	[AuthNumber] [int] NULL,
	[ExtCostDecimal] [int] NOT NULL,
 CONSTRAINT [PK_RCompanies] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RCompanies] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RConstants]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RConstants]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RConstants](
	[AAITableNum] [int] NOT NULL,
	[AAIDocType] [varchar](2) NOT NULL,
	[UnitCostDecimal] [int] NOT NULL,
	[ExtCostDecimal] [int] NOT NULL,
	[InventoryDecimal] [int] NOT NULL,
	[Threshold1] [decimal](18, 2) NOT NULL,
	[Threshold2] [decimal](18, 2) NOT NULL,
	[XferSOType] [varchar](2) NOT NULL,
	[XferPOType] [varchar](2) NOT NULL,
	[Company] [int] NOT NULL,
	[DirSOType] [varchar](2) NOT NULL,
	[DirPOType] [varchar](2) NOT NULL,
	[OOPOType] [varchar](2) NOT NULL,
	[CXDaysBack] [int] NOT NULL,
	[GLDaysBack] [int] NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RConstants] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RErrorMessages]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RErrorMessages]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RErrorMessages](
	[error] [int] NOT NULL,
	[description] [varchar](100) NOT NULL,
 CONSTRAINT [PK_RErrorMessages] PRIMARY KEY CLUSTERED 
(
	[error] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RErrorMessages] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RFiscalCalendar]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RFiscalCalendar]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RFiscalCalendar](
	[CompanyNumber] [varchar](5) NOT NULL,
	[CompanyName] [varchar](30) NOT NULL,
	[FiscalYear] [decimal](4, 0) NOT NULL,
	[FiscalPeriod] [int] NOT NULL,
	[YearBegins] [datetime] NOT NULL,
	[PeriodBegins] [datetime] NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[YearBeginsJ] [decimal](9, 0) NOT NULL,
	[PeriodBeginsJ] [decimal](8, 0) NOT NULL,
	[PeriodEndsJ] [decimal](8, 0) NOT NULL,
	[DaysinPeriod] [int] NOT NULL,
 CONSTRAINT [PK_RFiscalCalendar] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC,
	[FiscalYear] ASC,
	[FiscalPeriod] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RFiscalCalendar] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RHome_Page_Flow]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RHome_Page_Flow]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RHome_Page_Flow](
	[CompanyNumber] [nchar](10) NOT NULL,
	[Beginning_Var] [decimal](18, 2) NOT NULL,
	[GL_Variance] [decimal](18, 2) NOT NULL,
	[Perp_Variance] [decimal](18, 2) NOT NULL,
	[Trans_Variance] [decimal](18, 2) NOT NULL,
	[Out_Of_Balance] [decimal](18, 2) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
ALTER AUTHORIZATION ON [dbo].[RHome_Page_Flow] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RIndexDates]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RIndexDates]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RIndexDates](
	[CopyFromDate] [datetime] NOT NULL,
	[XferPOType] [varchar](2) NOT NULL,
	[XferSOType] [varchar](2) NOT NULL,
	[TransDate] [datetime] NOT NULL,
	[TransDateJ] [int] NOT NULL,
	[CopyFromDateJ] [int] NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RIndexDates] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RInvAccountList]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RInvAccountList]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RInvAccountList](
	[CompanyNumber] [varchar](5) NOT NULL,
	[ShortAccount] [varchar](8) NOT NULL,
	[BusinessUnit] [varchar](12) NOT NULL,
	[ObjectAccount] [varchar](6) NOT NULL,
	[SubAccount] [varchar](8) NOT NULL,
	[LongAccount] [varchar](29) NOT NULL,
	[AccountDescription] [varchar](30) NOT NULL,
	[From_Date] [datetime] NOT NULL,
	[To_Date] [datetime] NOT NULL,
	[Beginning_Balance] [decimal](18, 0) NOT NULL,
	[Sum_Details] [decimal](18, 0) NOT NULL,
	[Calculated_End_Bal] [decimal](18, 0) NOT NULL,
	[Actual_End_Bal] [decimal](18, 0) NOT NULL,
	[Variance] [decimal](18, 0) NOT NULL,
	[Unposted_Batches] [decimal](18, 0) NOT NULL,
	[Posted_Variance] [decimal](18, 0) NOT NULL,
	[Beginning_Balance_I] [decimal](18, 0) NOT NULL,
	[Sum_Details_I] [decimal](18, 0) NOT NULL,
	[Calculated_End_Bal_I] [decimal](18, 0) NOT NULL,
	[Actual_End_Bal_I] [decimal](18, 0) NOT NULL,
	[Variance_I] [decimal](18, 0) NOT NULL,
	[Unposted_Cardex] [decimal](18, 0) NOT NULL,
	[Posted_Variance_I] [decimal](18, 0) NOT NULL,
 CONSTRAINT [PK_RInvAccountList] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC,
	[ShortAccount] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RInvAccountList] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RInvAccountSummary]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RInvAccountSummary]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RInvAccountSummary](
	[CompanyNumber] [varchar](5) NOT NULL,
	[LongAccount] [varchar](29) NOT NULL,
	[PeriodBegins] [datetime] NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[BeginningBalance] [decimal](18, 2) NOT NULL,
	[PeriodGL] [decimal](18, 2) NOT NULL,
	[EndingGLBalance] [decimal](18, 2) NOT NULL,
	[GLRollOK] [varchar](8) NOT NULL,
	[UnpostedBatchAmount] [decimal](18, 2) NOT NULL,
	[PeriodCardex] [decimal](18, 2) NOT NULL,
	[PostedCardexAmount] [decimal](18, 2) NOT NULL,
	[PeriodUnpostedCardex] [decimal](18, 2) NOT NULL,
	[UnpostedCardexAmount] [decimal](18, 2) NOT NULL,
	[ProjectedBalance] [decimal](18, 2) NOT NULL,
	[AmountOnHand] [decimal](18, 2) NOT NULL,
	[AccountVariance] [decimal](18, 2) NOT NULL,
	[TransactionVariance] [decimal](18, 2) NOT NULL,
	[JournalEntries] [decimal](18, 2) NOT NULL,
	[OutOfBalance] [decimal](18, 2) NOT NULL,
	[OOBRollOK] [varchar](30) NOT NULL,
	[BalCXVar] [decimal](18, 2) NOT NULL,
	[AsOf] [bit] NOT NULL,
 CONSTRAINT [PK_RInvAccountSummary] PRIMARY KEY NONCLUSTERED 
(
	[CompanyNumber] ASC,
	[LongAccount] ASC,
	[PeriodEnds] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RInvAccountSummary] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RInvAsOf]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RInvAsOf]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RInvAsOf](
	[PeriodEnds] [datetime] NOT NULL,
	[CompanyNumber] [varchar](5) NOT NULL,
	[LongAccount] [varchar](29) NOT NULL,
	[BranchPlant] [varchar](12) NOT NULL,
	[ShortItem] [decimal](8, 0) NOT NULL,
	[ItemNumber] [varchar](25) NOT NULL,
	[Location] [varchar](20) NOT NULL,
	[Lot] [varchar](30) NOT NULL,
	[PeriodBegins] [datetime] NOT NULL,
	[GLClass] [char](4) NOT NULL,
	[PeriodCardex] [float] NOT NULL,
	[AmountOnHand] [float] NOT NULL,
	[PeriodQty] [float] NOT NULL,
	[QuantityonHand] [float] NOT NULL,
	[PrimaryUOM] [char](2) NOT NULL,
	[CatCode1] [char](3) NOT NULL,
	[CatCode2] [char](3) NOT NULL,
	[CatCode3] [char](3) NOT NULL,
	[CatCode4] [char](3) NOT NULL,
	[CatCode5] [char](3) NOT NULL,
	[UpdateFlag] [bit] NOT NULL,
	[RFQty] [float] NOT NULL,
	[RFAmt] [float] NOT NULL,
 CONSTRAINT [PK_RInvAsOf_1] PRIMARY KEY CLUSTERED 
(
	[PeriodEnds] ASC,
	[CompanyNumber] ASC,
	[LongAccount] ASC,
	[BranchPlant] ASC,
	[ShortItem] ASC,
	[Location] ASC,
	[Lot] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RInvAsOf] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RInvCosts]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RInvCosts]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RInvCosts](
	[ShortItem] [decimal](8, 0) NOT NULL,
	[BranchPlant] [varchar](12) NOT NULL,
	[ItemNumber] [varchar](25) NOT NULL,
	[Location] [varchar](20) NOT NULL,
	[Lot] [varchar](30) NOT NULL,
	[CostLevel] [varchar](1) NOT NULL,
	[CostMethod] [varchar](2) NOT NULL,
	[UnitCost] [decimal](18, 4) NOT NULL,
	[FrozenCost] [decimal](18, 4) NOT NULL,
 CONSTRAINT [PK_RInvCosts] PRIMARY KEY CLUSTERED 
(
	[ShortItem] ASC,
	[BranchPlant] ASC,
	[Location] ASC,
	[Lot] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RInvCosts] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RInvLedgerClasses]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RInvLedgerClasses]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RInvLedgerClasses](
	[CompanyNumber] [varchar](5) NOT NULL,
	[GLClass] [varchar](4) NOT NULL,
	[ProjectNumber] [varchar](12) NULL,
	[OnHandVariance] [decimal](18, 2) NOT NULL,
	[CardexVariance] [decimal](18, 2) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RInvLedgerClasses] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RInvoiceBatch]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RInvoiceBatch]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RInvoiceBatch](
	[CompanyNumber] [varchar](50) NOT NULL,
	[LongAccount] [varchar](50) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[GLDocType] [varchar](2) NOT NULL,
	[GLDocNumber] [decimal](8, 0) NOT NULL,
	[GLOrdType] [varchar](2) NOT NULL,
	[GLOrdNumber] [decimal](8, 0) NOT NULL,
	[GLOrdLine] [numeric](18, 3) NOT NULL,
	[CXDocType] [varchar](2) NOT NULL,
	[CxDocNumber] [decimal](8, 0) NOT NULL,
	[GLAmount] [decimal](18, 2) NOT NULL,
	[CXAmount] [decimal](18, 2) NOT NULL,
	[SumAmount] [decimal](18, 2) NOT NULL,
	[Reconciled] [varchar](1) NOT NULL,
	[UpdateCount] [int] NOT NULL,
 CONSTRAINT [PK_RInvoiceBatch] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC,
	[LongAccount] ASC,
	[PeriodEnds] ASC,
	[GLDocType] ASC,
	[GLDocNumber] ASC,
	[GLOrdType] ASC,
	[GLOrdNumber] ASC,
	[GLOrdLine] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RInvoiceBatch] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RMovementColumn]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RMovementColumn]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RMovementColumn](
	[ColumnNumber] [int] IDENTITY(1,1) NOT NULL,
	[ColumnTitle] [varchar](50) NOT NULL,
	[ColumnField] [varchar](50) NOT NULL,
	[ColumnCode1] [varchar](2) NULL,
	[ColumnCode2] [varchar](2) NULL,
	[ColumnCode3] [varchar](2) NULL,
	[ColumnCode4] [varchar](2) NULL,
	[ColumnCode5] [varchar](2) NULL,
	[ColumnCode6] [varchar](2) NULL,
	[ColumnSort] [int] NOT NULL,
 CONSTRAINT [PK_RMovementColumn] PRIMARY KEY CLUSTERED 
(
	[ColumnNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RMovementColumn] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RPeriodEnds]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RPeriodEnds]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RPeriodEnds](
	[CompanyNumber] [varchar](5) NOT NULL,
	[JulianDate] [decimal](6, 0) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[CDate] [datetime] NOT NULL,
 CONSTRAINT [PK_RPeriodEnds_1] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC,
	[CDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RPeriodEnds] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RPeriods]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RPeriods]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RPeriods](
	[Period] [int] NOT NULL,
 CONSTRAINT [PK_RPeriods] PRIMARY KEY CLUSTERED 
(
	[Period] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
ALTER AUTHORIZATION ON [dbo].[RPeriods] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RPerpetualInv]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RPerpetualInv]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RPerpetualInv](
	[CompanyNumber] [varchar](5) NOT NULL,
	[LongAccount] [varchar](29) NOT NULL,
	[BranchPlant] [varchar](12) NOT NULL,
	[ShortItem] [decimal](8, 0) NOT NULL,
	[ItemNumber] [varchar](25) NOT NULL,
	[ItemDescription] [varchar](30) NOT NULL,
	[Location] [varchar](20) NOT NULL,
	[Lot] [varchar](30) NOT NULL,
	[GLClass] [varchar](4) NOT NULL,
	[CostLevel] [varchar](1) NOT NULL,
	[CostMethod] [varchar](2) NOT NULL,
	[QuantityOnHand] [decimal](18, 2) NOT NULL,
	[QuantityinCardex] [decimal](18, 2) NOT NULL,
	[UnitCost] [decimal](18, 6) NOT NULL,
	[AmountOnHand] [decimal](18, 2) NOT NULL,
	[AmountInCardex] [decimal](18, 2) NOT NULL,
	[BaselineQOH] [decimal](18, 2) NOT NULL,
	[BaselineAOH] [decimal](18, 2) NOT NULL,
	[BaselineCX] [decimal](18, 2) NOT NULL,
	[DeltaAOH] [decimal](18, 2) NOT NULL,
	[DeltaCX] [decimal](18, 2) NOT NULL,
	[BaselineVar] [decimal](18, 2) NOT NULL,
	[EstUnits] [decimal](18, 2) NOT NULL,
	[LastUpdate] [decimal](18, 6) NOT NULL,
	[CardexUpdate] [decimal](18, 6) NOT NULL,
	[DocType] [varchar](2) NOT NULL,
	[DocNumber] [decimal](8, 0) NOT NULL,
	[DocAmount] [decimal](18, 2) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[Material] [decimal](18, 6) NOT NULL,
	[Labor] [decimal](18, 6) NOT NULL,
	[Overhead] [decimal](18, 6) NOT NULL,
	[Status] [varchar](1) NULL,
	[LastRec] [datetime] NOT NULL,
	[StockingType] [nchar](30) NOT NULL,
	[UnitOfMeasure] [nchar](2) NOT NULL,
	[SalesCategory01Code] [nchar](3) NOT NULL,
	[SalesCategory02Code] [nchar](3) NOT NULL,
	[SalesCategory03Code] [nchar](3) NOT NULL,
	[SalesCategory04Code] [nchar](3) NOT NULL,
	[SalesCategory05Code] [nchar](3) NOT NULL,
	[SalesCategory06Code] [nchar](6) NOT NULL,
	[SalesCategory07Code] [nchar](6) NOT NULL,
	[SalesCategory08Code] [nchar](6) NOT NULL,
	[SalesCategory09Code] [nchar](6) NOT NULL,
	[SalesCategory10Code] [nchar](6) NOT NULL,
	[PurchasingCategory01Code] [nchar](3) NOT NULL,
	[PurchasingCategory02Code] [nchar](3) NOT NULL,
	[PurchasingCategory03Code] [nchar](3) NOT NULL,
	[PurchasingCategory04Code] [nchar](3) NOT NULL,
	[PurchasingCategory05Code] [nchar](3) NOT NULL,
	[PurchasingCategory06Code] [nchar](6) NOT NULL,
	[PurchasingCategory07Code] [nchar](6) NOT NULL,
	[PurchasingCategory08Code] [nchar](6) NOT NULL,
	[PurchasingCategory09Code] [nchar](6) NOT NULL,
	[PurchasingCategory10Code] [nchar](6) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RPerpetualInv] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RRateBatches]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RRateBatches]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RRateBatches](
	[Company] [varchar](5) NOT NULL,
	[Batch] [decimal](8, 0) NOT NULL,
 CONSTRAINT [PK_RRateBatches] PRIMARY KEY CLUSTERED 
(
	[Company] ASC,
	[Batch] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RRateBatches] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RRateCX]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RRateCX]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RRateCX](
	[Company] [varchar](5) NOT NULL,
	[LongAccount] [varchar](29) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[DocType] [varchar](2) NOT NULL,
	[DocNumber] [decimal](8, 0) NOT NULL,
	[Batch] [decimal](8, 0) NOT NULL,
	[Amount] [decimal](18, 2) NOT NULL,
	[FrozenAmount] [decimal](18, 2) NOT NULL,
	[MatchingDocument] [decimal](8, 0) NOT NULL,
 CONSTRAINT [PK_RRateCX] PRIMARY KEY CLUSTERED 
(
	[Company] ASC,
	[LongAccount] ASC,
	[PeriodEnds] ASC,
	[DocType] ASC,
	[DocNumber] ASC,
	[Batch] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RRateCX] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RRateDocs]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RRateDocs]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RRateDocs](
	[Company] [varchar](5) NOT NULL,
	[DocNumber] [decimal](8, 0) NOT NULL,
 CONSTRAINT [PK_RRateDocs] PRIMARY KEY CLUSTERED 
(
	[Company] ASC,
	[DocNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RRateDocs] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RRateGL]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RRateGL]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RRateGL](
	[Company] [varchar](5) NOT NULL,
	[LongAccount] [varchar](29) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[DocType] [varchar](2) NOT NULL,
	[DocNumber] [decimal](8, 0) NOT NULL,
	[Batch] [decimal](8, 0) NOT NULL,
	[Amount] [decimal](18, 2) NOT NULL,
 CONSTRAINT [PK_RRateGL] PRIMARY KEY CLUSTERED 
(
	[Company] ASC,
	[LongAccount] ASC,
	[PeriodEnds] ASC,
	[DocType] ASC,
	[DocNumber] ASC,
	[Batch] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RRateGL] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RReceiptTypes]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RReceiptTypes]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RReceiptTypes](
	[DocType] [varchar](2) NOT NULL,
 CONSTRAINT [PK_ReceiptTypes] PRIMARY KEY CLUSTERED 
(
	[DocType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RReceiptTypes] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RServer_Log]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RServer_Log]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RServer_Log](
	[Time1] [datetime] NOT NULL,
	[Step] [varchar](50) NULL,
	[Process] [varchar](100) NULL,
	[UpdateCount] [int] NOT NULL,
	[Error] [varchar](100) NOT NULL,
	[ErrorNum] [int] NOT NULL,
	[Counter] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RServer_Log] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RServicePack]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RServicePack]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RServicePack](
	[Level] [varchar](25) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RServicePack] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RStandardUOMs]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RStandardUOMs]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RStandardUOMs](
	[UOM] [char](2) NOT NULL,
 CONSTRAINT [PK_RStandardUOMs_UOM] PRIMARY KEY CLUSTERED 
(
	[UOM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RStandardUOMs] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RSystemVariables]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RSystemVariables]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RSystemVariables](
	[Name] [varchar](50) NOT NULL,
	[Value] [varchar](500) NOT NULL,
 CONSTRAINT [PK_RSystemVariables] PRIMARY KEY CLUSTERED 
(
	[Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RSystemVariables] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RTimestamp]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RTimestamp]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RTimestamp](
	[CaptureStart] [varchar](25) NOT NULL,
	[LastCompleteRun] [varchar](25) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RTimestamp] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RunHistory]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RunHistory]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RunHistory](
	[Counter] [int] IDENTITY(1,1) NOT NULL,
	[StartTime] [varchar](25) NOT NULL,
	[RunDate] [varchar](25) NOT NULL,
	[Companies] [int] NOT NULL,
	[Accounts] [int] NOT NULL,
	[Baseline] [int] NOT NULL,
	[Locations] [int] NOT NULL,
	[Cardex] [int] NOT NULL,
	[GL] [int] NOT NULL,
	[BalCXVar] [decimal](18, 2) NOT NULL,
	[OOBalance] [decimal](18, 2) NULL,
	[Warnings] [int] NULL,
	[Errors] [int] NULL,
	[DaysBack] [int] NULL,
 CONSTRAINT [PK_RunHistory] PRIMARY KEY CLUSTERED 
(
	[Counter] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RunHistory] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RUnpostedBatches]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RUnpostedBatches]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RUnpostedBatches](
	[PeriodEnds] [datetime] NOT NULL,
	[UserName] [varchar](10) NOT NULL,
	[CompanyNumber] [varchar](5) NOT NULL,
	[LongAccount] [varchar](29) NOT NULL,
	[BatchNumber] [decimal](8, 0) NOT NULL,
	[BatchType] [varchar](2) NOT NULL,
	[OpenAmount] [decimal](18, 2) NOT NULL,
	[App] [char](25) NOT NULL,
	[Post] [char](25) NOT NULL,
 CONSTRAINT [PK_RUnpostedBatches] PRIMARY KEY CLUSTERED 
(
	[PeriodEnds] ASC,
	[UserName] ASC,
	[CompanyNumber] ASC,
	[LongAccount] ASC,
	[BatchNumber] ASC,
	[BatchType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RUnpostedBatches] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RUnpostedCardex]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RUnpostedCardex]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RUnpostedCardex](
	[CompanyNumber] [varchar](5) NOT NULL,
	[LongAccount] [varchar](29) NOT NULL,
	[DocType] [varchar](2) NOT NULL,
	[DocNumber] [decimal](8, 0) NOT NULL,
	[OrderType] [varchar](6) NOT NULL,
	[TransactionDate] [datetime] NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[TransactionAmount] [decimal](18, 2) NOT NULL,
	[Status] [char](3) NOT NULL,
	[BranchPlant] [char](12) NOT NULL,
 CONSTRAINT [PK_RUnpostedCardex] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC,
	[LongAccount] ASC,
	[DocType] ASC,
	[DocNumber] ASC,
	[OrderType] ASC,
	[TransactionDate] ASC,
	[PeriodEnds] ASC,
	[BranchPlant] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RUnpostedCardex] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RValidation]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RValidation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RValidation](
	[TableNumber] [varchar](15) NOT NULL,
	[Category] [varchar](15) NOT NULL,
	[OnHandQty] [numeric](30, 0) NOT NULL,
	[OnHandAmount] [numeric](30, 0) NOT NULL,
	[CardexAmount] [numeric](30, 0) NOT NULL,
	[GLAmount] [numeric](30, 0) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RValidation] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[RViewNames]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RViewNames]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RViewNames](
	[name] [varchar](250) NOT NULL,
	[report_type] [varchar](50) NOT NULL,
	[name_of_view] [varchar](100) NOT NULL,
	[view_description] [varchar](50) NOT NULL,
	[active] [bit] NOT NULL,
	[CrystalReportName] [varchar](50) NULL,
	[Sort] [int] NULL,
 CONSTRAINT [PK_RViewNames] PRIMARY KEY CLUSTERED 
(
	[name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[RViewNames] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[T0010]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[T0010]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[T0010](
	[Number] [int] IDENTITY(1,1) NOT NULL,
	[CCCO] [varchar](5) NOT NULL,
	[CCNAME] [varchar](30) NOT NULL,
	[CCDTPN] [varchar](1) NOT NULL,
	[CCDFYJ] [datetime] NOT NULL,
	[CCPNC] [decimal](9, 0) NOT NULL,
 CONSTRAINT [PK_T0010] PRIMARY KEY CLUSTERED 
(
	[CCCO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[T0010] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[T0902]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[T0902]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[T0902](
	[GBAID] [varchar](50) NOT NULL,
	[GBFY] [decimal](2, 0) NOT NULL,
	[GBLT] [varchar](2) NOT NULL,
	[GBCO] [varchar](5) NOT NULL,
	[GBAPYC] [decimal](17, 2) NULL,
	[GBAN01] [decimal](17, 2) NULL,
	[GBAN02] [decimal](17, 2) NULL,
	[GBAN03] [decimal](17, 2) NULL,
	[GBAN04] [decimal](17, 2) NULL,
	[GBAN05] [decimal](17, 2) NULL,
	[GBAN06] [decimal](17, 2) NULL,
	[GBAN07] [decimal](17, 2) NULL,
	[GBAN08] [decimal](17, 2) NULL,
	[GBAN09] [decimal](17, 2) NULL,
	[GBAN10] [decimal](17, 2) NULL,
	[GBAN11] [decimal](17, 2) NULL,
	[GBAN12] [decimal](17, 2) NULL,
	[GBAN13] [decimal](17, 2) NULL,
	[GBAN14] [decimal](17, 2) NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[T0902] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[T0911]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[T0911]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[T0911](
	[GLKCO] [varchar](5) NOT NULL,
	[GLCO] [varchar](5) NOT NULL,
	[GLDCT] [varchar](2) NOT NULL,
	[GLDOC] [decimal](8, 0) NOT NULL,
	[GLDCTO] [varchar](2) NOT NULL,
	[GLPDCT] [varchar](2) NOT NULL,
	[GLFY] [decimal](2, 0) NOT NULL,
	[GLPN] [decimal](2, 0) NOT NULL,
	[GLPOST] [varchar](1) NOT NULL,
	[GLICU] [decimal](8, 0) NOT NULL,
	[GLICUT] [varchar](2) NOT NULL,
	[GLAID] [varchar](8) NOT NULL,
	[GLMCU] [varchar](12) NOT NULL,
	[GLOBJ] [varchar](6) NOT NULL,
	[GLSUB] [varchar](8) NOT NULL,
	[GLDGJ] [datetime] NOT NULL,
	[GLAA] [float] NOT NULL,
	[GLUSER] [varchar](10) NOT NULL,
	[GLSBL] [varchar](8) NOT NULL,
	[GLANI] [varchar](29) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[GLPO] [varchar](8) NOT NULL,
	[GLLNID] [numeric](18, 3) NOT NULL,
	[GLR1] [varchar](8) NOT NULL,
	[GLR2] [varchar](8) NOT NULL,
	[Formatted] [tinyint] NOT NULL,
	[Prepped] [tinyint] NOT NULL,
	[Keyed] [tinyint] NOT NULL,
	[GLDICJ] [datetime] NOT NULL,
	[GLKey] [datetime] NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[T0911] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[T3112]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[T3112]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[T3112](
	[WLDOCO] [decimal](8, 0) NOT NULL,
	[WLDCTO] [char](2) NOT NULL,
	[WLMMCU] [char](12) NOT NULL,
	[WLVEND] [decimal](8, 0) NOT NULL,
	[WLRKCO] [char](5) NOT NULL,
	[WLRORN] [char](8) NOT NULL,
	[WLRCTO] [char](2) NOT NULL,
	[WLRLLN] [numeric](18, 0) NOT NULL,
	[WLUPMJ] [datetime] NOT NULL,
	[WLKITL] [varchar](25) NOT NULL,
	[WLOPSQ] [decimal](9, 0) NOT NULL,
	[Formatted] [tinyint] NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[T3112] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[T41021]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[T41021]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[T41021](
	[LIITM] [decimal](8, 0) NULL,
	[LIMCU] [varchar](12) NULL,
	[LILOCN] [varchar](20) NULL,
	[LILOTN] [varchar](30) NULL,
	[LIPBIN] [varchar](1) NULL,
	[LIGLPT] [varchar](4) NULL,
	[LILOTS] [varchar](1) NULL,
	[LILRCJ] [datetime] NULL,
	[LIPQOH] [float] NULL,
	[LIUPMJ] [datetime] NULL,
	[LITDAY] [decimal](9, 0) NULL,
	[LIKEY] [datetime] NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[T41021] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[T4105]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[T4105]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[T4105](
	[COITM] [decimal](8, 0) NOT NULL,
	[COMCU] [varchar](12) NOT NULL,
	[COLOCN] [varchar](20) NOT NULL,
	[COLOTN] [varchar](30) NOT NULL,
	[COLEDG] [varchar](2) NOT NULL,
	[COUNCS] [float] NULL,
	[COUPMJ] [datetime] NOT NULL,
	[Formatted] [tinyint] NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[T4105] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[T4111B]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[T4111B]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[T4111B](
	[ILKCOO] [varchar](5) NOT NULL,
	[ILKCO] [varchar](5) NOT NULL,
	[ILDCT] [varchar](2) NOT NULL,
	[ILDOC] [decimal](8, 0) NOT NULL,
	[ILDCTO] [varchar](2) NOT NULL,
	[ILMCU] [varchar](12) NOT NULL,
	[ILLITM] [varchar](25) NOT NULL,
	[ILLOCN] [varchar](20) NOT NULL,
	[ILLOTN] [varchar](30) NOT NULL,
	[ILGLPT] [varchar](4) NOT NULL,
	[ILDGL] [datetime] NOT NULL,
	[ILTRDJ] [datetime] NOT NULL,
	[ILPAID] [float] NOT NULL,
	[ILICU] [decimal](9, 0) NOT NULL,
	[InsertedInCXGL] [int] NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[InventoryAccount] [varchar](29) NOT NULL,
	[ILDOCO] [decimal](9, 0) NOT NULL,
	[ILLNID] [numeric](18, 3) NOT NULL,
	[ILCRDJ] [datetime] NOT NULL,
	[ILTDAY] [decimal](9, 0) NOT NULL,
	[ILIPCD] [varchar](1) NOT NULL,
	[Repaired] [varchar](10) NOT NULL,
	[ILTREF] [varchar](8) NOT NULL,
	[ILUKID] [decimal](18, 0) NOT NULL,
	[RCode] [varchar](30) NOT NULL,
	[GLAccount] [varchar](29) NOT NULL,
	[Formatted] [tinyint] NOT NULL,
	[RepFlag] [tinyint] NOT NULL,
	[Prepped] [tinyint] NOT NULL,
	[CXKey] [datetime] NOT NULL,
	[ILTREX] [varchar](30) NOT NULL,
	[ILUNCS] [float] NOT NULL,
	[ILTRUM] [char](2) NOT NULL,
	[ILTRQT] [float] NOT NULL,
	[PrimeFlag] [char](2) NOT NULL,
	[ILITM] [decimal](8, 0) NOT NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[T4111B] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[T4211]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[T4211]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[T4211](
	[SDKCOO] [varchar](5) NOT NULL,
	[SDDOCO] [decimal](8, 0) NOT NULL,
	[SDDCTO] [varchar](2) NOT NULL,
	[SDLNID] [numeric](18, 3) NOT NULL,
	[SDLITM] [varchar](25) NOT NULL,
	[SDUNCS] [decimal](18, 6) NOT NULL,
	[SDECST] [decimal](18, 2) NOT NULL,
	[SDTCST] [decimal](18, 6) NOT NULL,
	[SDUPRC] [float] NOT NULL,
	[SDDOC] [decimal](8, 0) NOT NULL,
	[SDDCT] [varchar](2) NOT NULL,
	[SDMCU] [varchar](12) NOT NULL,
	[SDCO] [varchar](5) NOT NULL,
	[SDDGL] [datetime] NOT NULL,
	[SDGLC] [varchar](4) NOT NULL,
	[SDLNTY] [varchar](2) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[SDCSTO] [varchar](1) NOT NULL,
	[SDSO01] [varchar](1) NOT NULL,
	[SDSO02] [varchar](1) NOT NULL,
	[SDLOCN] [varchar](20) NOT NULL,
	[SDLOTN] [varchar](30) NOT NULL,
	[SDRORN] [varchar](8) NOT NULL,
	[SDRCTO] [varchar](8) NOT NULL,
	[SDRLLN] [numeric](18, 3) NOT NULL,
	[SDTRDJ] [datetime] NOT NULL,
	[SDPQOR] [decimal](18, 2) NOT NULL,
	[SDAN8] [decimal](8, 0) NOT NULL,
	[SDSHAN] [decimal](8, 0) NOT NULL,
	[Formatted] [tinyint] NOT NULL,
	[SDLTTR] [varchar](3) NOT NULL,
	[SDNXTR] [varchar](3) NOT NULL,
	[SDUOM1] [varchar](2) NOT NULL,
	[SDAEXP] [decimal](18, 2) NOT NULL,
	[SDSOQS] [decimal](18, 2) NOT NULL,
	[SDUOM] [varchar](2) NOT NULL,
	[SDSOBK] [decimal](18, 2) NOT NULL,
	[SDOKC] [varchar](5) NULL,
	[SDODOC] [float] NULL,
	[SDODCT] [varchar](2) NULL,
	[SDOORN] [varchar](8) NULL,
	[SDOCTO] [varchar](2) NULL,
	[SDOKCO] [varchar](5) NULL,
	[SDOGNO] [numeric](18, 3) NULL,
	[SDRKCO] [varchar](5) NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[T4211] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[T42119]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[T42119]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[T42119](
	[SDKCOO] [varchar](5) NOT NULL,
	[SDDOCO] [decimal](8, 0) NOT NULL,
	[SDDCTO] [varchar](2) NOT NULL,
	[SDLNID] [numeric](18, 3) NOT NULL,
	[SDLITM] [varchar](25) NOT NULL,
	[SDUNCS] [decimal](18, 6) NOT NULL,
	[SDECST] [decimal](18, 2) NOT NULL,
	[SDTCST] [decimal](18, 6) NOT NULL,
	[SDDOC] [decimal](8, 0) NOT NULL,
	[SDDCT] [varchar](2) NOT NULL,
	[SDMCU] [varchar](12) NOT NULL,
	[SDCO] [varchar](5) NOT NULL,
	[SDDGL] [datetime] NOT NULL,
	[SDGLC] [varchar](4) NOT NULL,
	[SDLNTY] [varchar](2) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[SDCSTO] [varchar](1) NOT NULL,
	[SDSO01] [varchar](1) NOT NULL,
	[SDSO02] [varchar](1) NOT NULL,
	[SDLOCN] [varchar](20) NOT NULL,
	[SDLOTN] [varchar](30) NOT NULL,
	[SDRORN] [varchar](8) NOT NULL,
	[SDRCTO] [varchar](2) NOT NULL,
	[SDRLLN] [decimal](18, 3) NOT NULL,
	[SDPQOR] [decimal](18, 4) NOT NULL,
	[SDUPRC] [float] NOT NULL,
	[SDAN8] [decimal](8, 0) NOT NULL,
	[SDSHAN] [decimal](8, 0) NOT NULL,
	[Formatted] [tinyint] NOT NULL,
	[SDUPMJ] [datetime] NOT NULL,
	[SDTDAY] [decimal](9, 0) NOT NULL,
	[SDKEY] [datetime] NOT NULL,
	[SDNXTR] [varchar](3) NOT NULL,
	[SDLTTR] [varchar](3) NOT NULL,
	[SDUOM1] [varchar](2) NOT NULL,
	[SDAEXP] [decimal](18, 2) NOT NULL,
	[SDSOQS] [decimal](18, 2) NOT NULL,
	[SDUOM] [varchar](2) NOT NULL,
	[SDSOBK] [decimal](18, 2) NOT NULL,
	[SDOKC] [varchar](5) NULL,
	[SDODOC] [float] NULL,
	[SDODCT] [varchar](2) NULL,
	[SDOORN] [varchar](8) NULL,
	[SDOCTO] [varchar](2) NULL,
	[SDOKCO] [varchar](5) NULL,
	[SDOGNO] [numeric](18, 3) NULL,
	[SDRKCO] [varchar](5) NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[T42119] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[T4311]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[T4311]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[T4311](
	[PDKCOO] [varchar](5) NOT NULL,
	[PDDOCO] [decimal](8, 0) NOT NULL,
	[PDDCTO] [varchar](2) NOT NULL,
	[PDSFXO] [nchar](3) NULL,
	[PDLNID] [numeric](18, 3) NOT NULL,
	[PDLITM] [varchar](25) NOT NULL,
	[PDPRRC] [float] NOT NULL,
	[PDAEXP] [float] NOT NULL,
	[PDMCU] [varchar](12) NOT NULL,
	[PDCO] [varchar](5) NOT NULL,
	[PDDGL] [datetime] NOT NULL,
	[PDGLC] [varchar](4) NOT NULL,
	[PDLNTY] [varchar](2) NOT NULL,
	[PeriodEnds] [datetime] NOT NULL,
	[PDLOCN] [varchar](20) NOT NULL,
	[PDLOTN] [varchar](30) NOT NULL,
	[PDRORN] [varchar](8) NOT NULL,
	[PDRCTO] [varchar](8) NOT NULL,
	[PDRLLN] [numeric](18, 3) NOT NULL,
	[PDTRDJ] [datetime] NOT NULL,
	[PDPQOR] [float] NOT NULL,
	[PDAN8] [decimal](8, 0) NOT NULL,
	[PDSHAN] [decimal](8, 0) NOT NULL,
	[PDAOPN] [decimal](18, 2) NOT NULL,
	[PDAREC] [decimal](18, 2) NOT NULL,
	[Formatted] [tinyint] NOT NULL,
	[PDUOPN] [float] NOT NULL,
	[PDUREC] [decimal](18, 4) NOT NULL,
	[PDKEY] [datetime] NOT NULL,
	[PDLTTR] [varchar](3) NOT NULL,
	[PDNXTR] [varchar](3) NOT NULL,
	[PDUOM] [varchar](2) NOT NULL,
	[PDRKCO] [varchar](5) NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[T4311] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[UserCompany]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UserCompany]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[UserCompany](
	[UserID] [char](10) NOT NULL,
	[CompanyNumber] [varchar](5) NOT NULL,
 CONSTRAINT [PK_UserCompany] PRIMARY KEY CLUSTERED 
(
	[UserID] ASC,
	[CompanyNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[UserCompany] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[Users]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Users]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Users](
	[UserID] [char](10) NOT NULL,
	[Password] [varchar](50) NULL,
	[active] [bit] NULL,
	[UserTypeID] [int] NOT NULL,
 CONSTRAINT [PK_Users_UserID] PRIMARY KEY CLUSTERED 
(
	[UserID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[Users] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[UserTypes]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UserTypes]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[UserTypes](
	[UserTypeID] [int] IDENTITY(1,1) NOT NULL,
	[UserType] [varchar](50) NULL,
 CONSTRAINT [PK_UserTypes_UserTypeID] PRIMARY KEY CLUSTERED 
(
	[UserTypeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, DATA_COMPRESSION = PAGE) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[UserTypes] TO  SCHEMA OWNER 
GO
USE [FB91DWCR2]
GO
/****** Object:  Table [dbo].[JDESFWOCrossReferenceFile]    Script Date: 5/8/13 12:13:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDESFWOCrossReferenceFile]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDESFWOCrossReferenceFile](
	[SourceID] [int] NOT NULL,
	[Source] [nchar](20) NOT NULL,
	[OrderNumber] [int] NOT NULL,
	[DocumentNumber] [int] NOT NULL,
	[DocumentType] [nchar](2) NOT NULL,
	[GLDate] [datetime] NOT NULL,
	[BatchNumber] [int] NOT NULL,
	[BatchType] [nchar](2) NOT NULL,
	[BatchDate] [datetime] NOT NULL,
	[UserID] [nchar](10) NOT NULL,
	[ProgramID] [nchar](10) NOT NULL,
	[WorkStationID] [nchar](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDESFWOCrossReferenceFile] PRIMARY KEY CLUSTERED 
(
	[OrderNumber] ASC,
	[DocumentNumber] ASC,
	[GLDate] ASC,
	[BatchType] ASC,
	[UserID] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
ALTER AUTHORIZATION ON [dbo].[JDESFWOCrossReferenceFile] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDESFControlRoutingInstruct]    Script Date: 5/8/13 12:13:21 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDESFControlRoutingInstruct]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDESFControlRoutingInstruct](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[OrderNumber] [int] NOT NULL,
	[OrderTypeCode] [char](2) NOT NULL,
	[OrderSuffix] [char](3) NOT NULL,
	[CompanyNumber] [char](5) NOT NULL,
	[TypeofRouting] [char](3) NOT NULL,
	[ParentItemNumber] [int] NOT NULL,
	[ItemNumber2ndKit] [char](25) NOT NULL,
	[ItemNumber3rdKit] [char](25) NOT NULL,
	[Branch] [char](12) NOT NULL,
	[LineCellIdentifier] [char](12) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[AutoLoadDescription] [char](4) NOT NULL,
	[Description01] [char](30) NOT NULL,
	[OperationsSequenceNumber] [decimal](20, 7) NOT NULL,
	[TypeOperationCode] [char](2) NOT NULL,
	[OperationStatusCodeWO] [char](2) NOT NULL,
	[InspectionCode] [char](2) NOT NULL,
	[TimeBasis] [char](1) NOT NULL,
	[LabororMachine] [char](1) NOT NULL,
	[PayPointCode] [char](1) NOT NULL,
	[PayPointStatus] [char](1) NOT NULL,
	[JobType] [char](6) NOT NULL,
	[AddressNumber] [int] NOT NULL,
	[CriticalRatio] [decimal](20, 7) NOT NULL,
	[SlackTimeRatio] [decimal](20, 7) NOT NULL,
	[TransactionDate] [datetime] NOT NULL,
	[RequestedDate] [datetime] NOT NULL,
	[DateStartJulian] [datetime] NOT NULL,
	[DateCompletionJulian] [datetime] NOT NULL,
	[TimeBeginningHHMMSS] [int] NOT NULL,
	[TimeEndingHHMMSS] [int] NOT NULL,
	[ShiftCodeRequested] [char](1) NOT NULL,
	[ShiftCodeStart] [char](1) NOT NULL,
	[ShiftCodeCompleted] [char](1) NOT NULL,
	[PercentLeadtimeOverlap] [decimal](20, 7) NOT NULL,
	[PercentOverlap] [decimal](20, 7) NOT NULL,
	[PercentOperationalPlannedYield] [decimal](20, 7) NOT NULL,
	[PercentCumulativePlannedYield] [decimal](20, 7) NOT NULL,
	[SequenceNumberNextOperation] [decimal](20, 7) NOT NULL,
	[CrewSize] [decimal](20, 7) NOT NULL,
	[MoveHours] [decimal](20, 7) NOT NULL,
	[QueueHours] [decimal](20, 7) NOT NULL,
	[RunMachineStandard] [decimal](20, 7) NOT NULL,
	[RunLaborStandard] [decimal](20, 7) NOT NULL,
	[StandardSetupHours] [decimal](20, 7) NOT NULL,
	[RunMachineActual] [decimal](20, 7) NOT NULL,
	[RunLaborActual] [decimal](20, 7) NOT NULL,
	[HoursSetupLaborHoursActual] [decimal](20, 7) NOT NULL,
	[FactorOperationShrinkageFactor] [decimal](20, 7) NOT NULL,
	[QuantityOrdered] [decimal](22, 7) NOT NULL,
	[QuantityCanceled] [decimal](22, 7) NOT NULL,
	[QuantityShipped] [decimal](22, 7) NOT NULL,
	[UnitsQuantityatOperation] [decimal](22, 7) NOT NULL,
	[RatePiecework] [decimal](20, 7) NOT NULL,
	[UnitOfMeasureAsInput] [char](2) NOT NULL,
	[HoursUnaccountedDirectLabor] [decimal](20, 7) NOT NULL,
	[HoursUnaccountedSetupLabor] [decimal](20, 7) NOT NULL,
	[HoursUnaccountedMachineHours] [decimal](20, 7) NOT NULL,
	[AmountUnaccountedDirectLabor] [decimal](20, 7) NOT NULL,
	[AmountUnaccountedSetupLabor] [decimal](20, 7) NOT NULL,
	[AmountUnaccountedMachine] [decimal](20, 7) NOT NULL,
	[UnitorTagNumber] [char](12) NOT NULL,
	[MessageNumber] [char](10) NOT NULL,
	[PurchasingBusinessUnit] [char](12) NOT NULL,
	[ObjectAccount] [char](6) NOT NULL,
	[Subsidiary] [char](8) NOT NULL,
	[PrimaryLastSupplierNumber] [int] NOT NULL,
	[RelatedOrderKeyCompany] [char](5) NOT NULL,
	[RelatedPoSoWoNumber] [char](8) NOT NULL,
	[RelatedPoSoWoType] [char](2) NOT NULL,
	[RelatedPOSOLineNumber] [decimal](20, 7) NOT NULL,
	[DocumentType] [char](2) NOT NULL,
	[UserReservedCode] [char](2) NOT NULL,
	[UserReservedDate] [datetime] NOT NULL,
	[UserReservedAmount] [decimal](20, 7) NOT NULL,
	[UserReservedReference] [char](15) NOT NULL,
	[UserReservedNumber] [int] NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[Location] [char](20) NOT NULL,
	[Resourceunitsconsumed] [decimal](20, 7) NOT NULL,
	[CapacityUnitofmeasure] [char](2) NOT NULL,
	[WorkcenterBranch] [char](12) NOT NULL,
	[RunMachineCurrent] [decimal](20, 7) NOT NULL,
	[RunLaborCurrent] [decimal](20, 7) NOT NULL,
	[SetupLaborCurrent] [decimal](20, 7) NOT NULL,
	[CostComponent] [char](3) NOT NULL,
	[ActivityBasedCostingActCode] [char](10) NOT NULL,
	[AssetItemNumber] [decimal](20, 7) NOT NULL,
	[AmountUnaccountedScrap] [decimal](20, 7) NOT NULL,
	[UnitsUnaccountedScrap] [decimal](22, 7) NOT NULL,
	[HoursUnaccountedDirectLaborS9] [decimal](20, 7) NOT NULL,
	[RunLaborRate] [decimal](20, 7) NOT NULL,
	[RunMachineRate] [decimal](20, 7) NOT NULL,
	[SetupLaborRate] [decimal](20, 7) NOT NULL,
	[ConstraintsFlag] [char](1) NOT NULL,
	[TimeScheduledStartHHMMSS] [int] NOT NULL,
	[TimeScheduledEndHHMMSS] [int] NOT NULL,
	[TimeCompleted] [int] NOT NULL,
	[DateActualStart] [datetime] NOT NULL,
	[TimeStartHHMMSS] [int] NOT NULL,
	[CompetencyType] [char](3) NOT NULL,
	[CompetencyCode] [char](10) NOT NULL,
	[CompetencyLevelFrom] [decimal](20, 7) NOT NULL,
	[CompetencyLevelTo] [decimal](20, 7) NOT NULL,
	[RuleMatchFlag] [char](1) NOT NULL,
	[AddressNumberManager] [int] NOT NULL,
	[Supervisor] [int] NOT NULL,
	[AddressNumberAssignedTo] [int] NOT NULL,
	[MaintenanceScheduleFlag] [char](1) NOT NULL,
	[ResourcesAssigned] [char](1) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDESFShopFloorControlRoutingInstructions] PRIMARY KEY CLUSTERED 
(
	[OrderNumber] ASC,
	[BusinessUnitCode] ASC,
	[OperationsSequenceNumber] ASC,
	[TypeOperationCode] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDESFControlRoutingInstruct] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEPDItemCostComponent]    Script Date: 5/8/13 12:13:21 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEPDItemCostComponent]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEPDItemCostComponent](
	[SourceID] [int] NOT NULL,
	[Source] [nchar](20) NOT NULL,
	[ItemNumber] [int] NOT NULL,
	[ItemNumber02] [nchar](25) NOT NULL,
	[ItemNumber03] [nchar](25) NOT NULL,
	[Branch] [nchar](12) NOT NULL,
	[Location] [nchar](20) NOT NULL,
	[LotNumber] [nchar](30) NOT NULL,
	[CostMethodCode] [nchar](2) NOT NULL,
	[CostType] [nchar](3) NOT NULL,
	[LotGrade] [nchar](3) NOT NULL,
	[ManufacturedCostFrozen] [decimal](20, 7) NOT NULL,
	[ManufacturedCostSimulated] [decimal](20, 7) NOT NULL,
	[CostRollupFrozen] [decimal](20, 7) NOT NULL,
	[CostRollupSimulated] [decimal](20, 7) NOT NULL,
	[FactorCodeFrozen] [nchar](4) NOT NULL,
	[FactorCodeSimulated] [nchar](4) NOT NULL,
	[FactorFrozen] [decimal](15, 4) NOT NULL,
	[FactorSimulated] [decimal](15, 4) NOT NULL,
	[RateCodeFrozen] [nchar](4) NOT NULL,
	[RateCodeSimulated] [nchar](4) NOT NULL,
	[RateFrozen] [decimal](20, 7) NOT NULL,
	[RateSimulated] [decimal](20, 7) NOT NULL,
	[ProcessingFlag] [nchar](1) NOT NULL,
	[UserID] [nchar](10) NOT NULL,
	[ProgramID] [nchar](10) NOT NULL,
	[WorkStationID] [nchar](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[SequenceNumberOperations] [decimal](20, 7) NOT NULL,
	[AlternateWorkCenter] [nchar](24) NOT NULL,
	[WorkcenterBranch] [nchar](24) NOT NULL,
	[AccountLevelofDetail] [nchar](2) NOT NULL,
	[TypeBillofMaterial] [nchar](6) NOT NULL,
	[QuantityAccountingCost] [int] NOT NULL,
	[DetailFlag] [nchar](2) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEPDItemCostComponent] PRIMARY KEY CLUSTERED 
(
	[ItemNumber] ASC,
	[Branch] ASC,
	[Location] ASC,
	[LotNumber] ASC,
	[CostMethodCode] ASC,
	[CostType] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
ALTER AUTHORIZATION ON [dbo].[JDEPDItemCostComponent] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEINUOMstandardConversion]    Script Date: 5/8/13 12:13:21 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEINUOMstandardConversion]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEINUOMstandardConversion](
	[SourceID] [int] NOT NULL,
	[Source] [nchar](20) NOT NULL,
	[UnitOfMeasure] [nchar](2) NOT NULL,
	[RelatedUnitOfMeasure] [nchar](2) NOT NULL,
	[ConversionFactor] [decimal](20, 7) NOT NULL,
	[UserID] [nchar](10) NOT NULL,
	[ProgramID] [nchar](10) NOT NULL,
	[WorkStationID] [nchar](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[ExcludefromPO] [nchar](2) NOT NULL,
	[ExcludefromSO] [nchar](2) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEINUOMStandardConversion] PRIMARY KEY CLUSTERED 
(
	[UnitOfMeasure] ASC,
	[RelatedUnitOfMeasure] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
ALTER AUTHORIZATION ON [dbo].[JDEINUOMstandardConversion] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEINUOMConversionFactors]    Script Date: 5/8/13 12:13:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEINUOMConversionFactors]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEINUOMConversionFactors](
	[SOURCE] [char](20) NOT NULL,
	[SourceID] [int] NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[ItemNumber] [int] NOT NULL,
	[UnitOfMeasure] [char](2) NOT NULL,
	[RelatedUnitOfMeasure] [char](2) NOT NULL,
	[UnitOfMeasureStructure] [char](1) NOT NULL,
	[ConversionFactor] [decimal](20, 7) NOT NULL,
	[ConvFactorSecondaryToPrimary] [decimal](20, 7) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[ExcludefromPO] [char](2) NOT NULL,
	[ExcludefromSO] [char](2) NOT NULL,
	[CodePurchasePriceCode] [decimal](20, 7) NOT NULL,
	[CodeSalesPriceCode] [decimal](20, 7) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEINUOMConversionFactors] PRIMARY KEY CLUSTERED 
(
	[BusinessUnitCode] ASC,
	[ItemNumber] ASC,
	[UnitOfMeasure] ASC,
	[RelatedUnitOfMeasure] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEINUOMConversionFactors] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEINLotMaster]    Script Date: 5/8/13 12:13:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEINLotMaster]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEINLotMaster](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[LotNumber] [char](30) NOT NULL,
	[LotDescription] [char](30) NOT NULL,
	[LotStatusCode] [char](1) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[ItemNumber] [int] NOT NULL,
	[ItemNumber02] [char](25) NOT NULL,
	[ItemNumber03] [char](25) NOT NULL,
	[PrimaryLastSupplierNumber] [int] NOT NULL,
	[OrderNumberDocumentCompany] [char](5) NOT NULL,
	[OrderNumber] [int] NOT NULL,
	[OrderTypeCode] [char](2) NOT NULL,
	[SupplierLot] [char](30) NOT NULL,
	[LotPotency] [decimal](15, 3) NOT NULL,
	[LotGrade] [char](3) NOT NULL,
	[LotExpirationDate] [datetime] NOT NULL,
	[LotSerialNumber] [char](30) NOT NULL,
	[UserDefinedDate01] [datetime] NOT NULL,
	[UserDefinedDate02] [datetime] NOT NULL,
	[UserDefinedDate03] [datetime] NOT NULL,
	[UserDefinedDate04] [datetime] NOT NULL,
	[UserDefinedDate05] [datetime] NOT NULL,
	[UserDefinedDate06] [datetime] NOT NULL,
	[UserDefinedQuantity01] [decimal](22, 7) NOT NULL,
	[UserDefinedQuantity02] [decimal](22, 7) NOT NULL,
	[UserDefinedQuantity03] [decimal](22, 7) NOT NULL,
	[UserDefinedQuantity04] [decimal](22, 7) NOT NULL,
	[UserDefinedQuantity05] [decimal](22, 7) NOT NULL,
	[UserDefinedQuantity06] [decimal](22, 7) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[LotCategory01Code] [char](3) NOT NULL,
	[LotCategory01] [char](30) NOT NULL,
	[LotCategory02Code] [char](3) NOT NULL,
	[LotCategory02] [char](30) NOT NULL,
	[LotCategory03Code] [char](3) NOT NULL,
	[LotCategory03] [char](30) NOT NULL,
	[LotCategory04Code] [char](3) NOT NULL,
	[LotCategory04] [char](30) NOT NULL,
	[LotCategory05Code] [char](3) NOT NULL,
	[LotCategory05] [char](30) NOT NULL,
	[LotCategory06Code] [char](3) NOT NULL,
	[LotCategory06] [char](30) NOT NULL,
	[LotCategory07Code] [char](3) NOT NULL,
	[LotCategory07] [char](30) NOT NULL,
	[LotCategory08Code] [char](3) NOT NULL,
	[LotCategory08] [char](30) NOT NULL,
	[LotCategory09Code] [char](3) NOT NULL,
	[LotCategory09] [char](30) NOT NULL,
	[LotCategory10Code] [char](3) NOT NULL,
	[LotCategory10] [char](30) NOT NULL,
	[MemoLot01] [char](30) NOT NULL,
	[MemoLot02] [char](30) NOT NULL,
	[MemoLot03] [char](30) NOT NULL,
	[BestBeforeDate] [datetime] NOT NULL,
	[BasedOnDate] [datetime] NOT NULL,
	[LotEffectivityDate] [datetime] NOT NULL,
	[OnHandDate] [datetime] NOT NULL,
	[SellByDate] [datetime] NOT NULL,
	[UserLotDate1] [datetime] NOT NULL,
	[UserLotDate2] [datetime] NOT NULL,
	[UserLotDate3] [datetime] NOT NULL,
	[UserLotDate4] [datetime] NOT NULL,
	[UserLotDate5] [datetime] NOT NULL,
	[CriticalHoldFlag] [char](1) NOT NULL,
	[WorkFlowPendingFlag] [char](1) NOT NULL,
	[DocumentOrder#Invoiceetc] [int] NOT NULL,
	[LotReusable] [char](1) NOT NULL,
	[LotStatusCodeExpanded] [char](3) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEINLotMaster] PRIMARY KEY CLUSTERED 
(
	[LotNumber] ASC,
	[ItemNumber] ASC,
	[BusinessUnitCode] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEINLotMaster] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEINItemMaster]    Script Date: 5/8/13 12:13:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEINItemMaster]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEINItemMaster](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[ItemNumber] [int] NOT NULL,
	[ItemNumber02] [char](25) NOT NULL,
	[ItemNumber03] [char](25) NOT NULL,
	[Description01] [char](30) NOT NULL,
	[Description02] [char](30) NOT NULL,
	[SearchText] [char](30) NOT NULL,
	[SearchTextCompressed] [char](30) NOT NULL,
	[SalesCategory01Code] [char](3) NOT NULL,
	[SalesCategory01] [char](30) NOT NULL,
	[SalesCategory02Code] [char](3) NOT NULL,
	[SalesCategory02] [char](30) NOT NULL,
	[SalesCategory03Code] [char](3) NOT NULL,
	[SalesCategory03] [char](30) NOT NULL,
	[SalesCategory04Code] [char](3) NOT NULL,
	[SalesCategory04] [char](30) NOT NULL,
	[SalesCategory05Code] [char](3) NOT NULL,
	[SalesCategory05] [char](30) NOT NULL,
	[SalesCategory06Code] [char](6) NOT NULL,
	[SalesCategory06] [char](30) NOT NULL,
	[SalesCategory07Code] [char](6) NOT NULL,
	[SalesCategory07] [char](30) NOT NULL,
	[SalesCategory08Code] [char](6) NOT NULL,
	[SalesCategory08] [char](30) NOT NULL,
	[SalesCategory09Code] [char](6) NOT NULL,
	[SalesCategory09] [char](30) NOT NULL,
	[SalesCategory10Code] [char](6) NOT NULL,
	[SalesCategory10] [char](30) NOT NULL,
	[PurchasingCategory01Code] [char](3) NOT NULL,
	[PurchasingCategory01] [char](30) NOT NULL,
	[PurchasingCategory02Code] [char](3) NOT NULL,
	[PurchasingCategory02] [char](30) NOT NULL,
	[PurchasingCategory03Code] [char](3) NOT NULL,
	[PurchasingCategory03] [char](30) NOT NULL,
	[PurchasingCategory04Code] [char](3) NOT NULL,
	[PurchasingCategory04] [char](30) NOT NULL,
	[PurchasingCategory05Code] [char](3) NOT NULL,
	[PurchasingCategory05] [char](30) NOT NULL,
	[PurchasingCategory06Code] [char](6) NOT NULL,
	[PurchasingCategory06] [char](30) NOT NULL,
	[PurchasingCategory07Code] [char](6) NOT NULL,
	[PurchasingCategory07] [char](30) NOT NULL,
	[PurchasingCategory08Code] [char](6) NOT NULL,
	[PurchasingCategory08] [char](30) NOT NULL,
	[PurchasingCategory09Code] [char](6) NOT NULL,
	[PurchasingCategory09] [char](30) NOT NULL,
	[PurchasingCategory10Code] [char](6) NOT NULL,
	[PurchasingCategory10] [char](30) NOT NULL,
	[CommodityCode] [char](15) NOT NULL,
	[ProductGroupCode] [char](3) NOT NULL,
	[ProductGroup] [char](30) NOT NULL,
	[DispatchGroup] [char](3) NOT NULL,
	[ItemPriceGroupCode] [char](8) NOT NULL,
	[ItemPrice] [char](30) NOT NULL,
	[BasketRepriceGroup] [char](8) NOT NULL,
	[OrderRepriceGroup] [char](8) NOT NULL,
	[BuyerNumber] [int] NOT NULL,
	[DrawingNumber] [char](20) NOT NULL,
	[LastRevisionNumber] [char](2) NOT NULL,
	[DrawingSize] [char](1) NOT NULL,
	[VolumeCubicDimension] [decimal](20, 7) NOT NULL,
	[PreferredCarrierSales] [int] NOT NULL,
	[PreferredCarrierPurchasing] [int] NOT NULL,
	[ShippingConditionsCode] [char](3) NOT NULL,
	[ShippingCommodityClass] [char](3) NOT NULL,
	[UnitOfMeasurePrimary] [char](2) NOT NULL,
	[UnitOfMeasureSecondary] [char](2) NOT NULL,
	[UnitOfMeasurePurchas] [char](2) NOT NULL,
	[UnitOfMeasurePricing] [char](2) NOT NULL,
	[UnitOfMeasureShipping] [char](2) NOT NULL,
	[UnitOfMeasureProduction] [char](2) NOT NULL,
	[UnitOfMeasureAllocation] [char](2) NOT NULL,
	[UnitOfMeasureWeight] [char](2) NOT NULL,
	[UOMVolume] [char](2) NOT NULL,
	[UOMStocking] [char](2) NOT NULL,
	[UOMVolumeOrWeightPSAU] [char](1) NOT NULL,
	[CycleCountCategory] [char](3) NOT NULL,
	[GLCategory] [char](4) NOT NULL,
	[SalesPriceLevel] [char](1) NOT NULL,
	[PurchasePriceLevel] [char](1) NOT NULL,
	[InventoryCostLevel] [char](1) NOT NULL,
	[GradePotencyPricing] [char](1) NOT NULL,
	[CheckAvailability] [char](1) NOT NULL,
	[BulkPackedFlag] [char](1) NOT NULL,
	[LayerCodeSource] [char](1) NOT NULL,
	[PotencyControl] [char](1) NOT NULL,
	[GradeControl] [char](1) NOT NULL,
	[StandardPotency] [decimal](20, 7) NOT NULL,
	[FromPotency] [decimal](20, 7) NOT NULL,
	[ThruPotency] [decimal](20, 7) NOT NULL,
	[StandardGrade] [char](3) NOT NULL,
	[FromGrade] [char](3) NOT NULL,
	[ThruGrade] [char](3) NOT NULL,
	[ComponentType] [char](1) NOT NULL,
	[StockingTypeCode] [char](1) NOT NULL,
	[StockingType] [char](30) NOT NULL,
	[LineType] [char](2) NOT NULL,
	[ContractItem] [char](1) NOT NULL,
	[BackOrdersAllowed] [char](1) NOT NULL,
	[ItemFlashMessage] [char](2) NOT NULL,
	[TempFlashMessage] [char](2) NOT NULL,
	[PrintMessage] [char](10) NOT NULL,
	[ABCCode1Sales] [char](1) NOT NULL,
	[ABCCode2Margin] [char](1) NOT NULL,
	[ABCCode3Investment] [char](1) NOT NULL,
	[ABCCodeOverrideIndicator] [char](1) NOT NULL,
	[TypeWarranty] [char](8) NOT NULL,
	[CommissionCategory] [char](8) NOT NULL,
	[SerialNumberRequired] [char](1) NOT NULL,
	[KitPricingMethod] [char](1) NOT NULL,
	[FIFOProcessing] [char](1) NOT NULL,
	[LotStatusCode] [char](1) NOT NULL,
	[ShelfLifeDays] [int] NOT NULL,
	[PlannerNumber] [int] NOT NULL,
	[PlanningCode] [char](1) NOT NULL,
	[PercentMargin] [decimal](20, 7) NOT NULL,
	[MarginMaintenance] [decimal](20, 7) NOT NULL,
	[PartStatusCode] [char](2) NOT NULL,
	[RoundToWholeNumber] [char](1) NOT NULL,
	[LeadtimeLevel] [int] NOT NULL,
	[LeadtimeManufacturing] [int] NOT NULL,
	[LeadtimeCumulative] [int] NOT NULL,
	[OrderPolicyCode] [char](1) NOT NULL,
	[ValueOrderPolicy] [decimal](15, 0) NOT NULL,
	[AccountingCostQuantity] [decimal](22, 7) NOT NULL,
	[MFGLeadtimeQuantity] [decimal](22, 7) NOT NULL,
	[LeadtimePerUnit] [decimal](20, 7) NOT NULL,
	[PlanningFenceRule] [char](1) NOT NULL,
	[FixedVariableLeadtime] [char](1) NOT NULL,
	[IssueTypeCode] [char](1) NOT NULL,
	[OrderWith] [char](1) NOT NULL,
	[PlanningFence] [int] NOT NULL,
	[FreezeFence] [int] NOT NULL,
	[MessageDisplayFence] [int] NOT NULL,
	[TimeFence] [int] NOT NULL,
	[ShipmentLeadtimeOffset] [int] NOT NULL,
	[ExpediteDamperDays] [int] NOT NULL,
	[DeferDamperDays] [int] NOT NULL,
	[SafetyLeadtime] [int] NOT NULL,
	[MakeBuyCode] [char](1) NOT NULL,
	[CoProductByProductIntermediate] [char](1) NOT NULL,
	[LowLevelCode] [int] NOT NULL,
	[CommitmentMethod] [char](1) NOT NULL,
	[SpecificCommitmentDays] [int] NOT NULL,
	[ConfiguredStringIDNextNumber] [int] NOT NULL,
	[UserReservedCode] [char](2) NOT NULL,
	[UserReservedDate] [datetime] NOT NULL,
	[UserReservedAmount] [decimal](20, 7) NOT NULL,
	[UserReservedNumber] [int] NOT NULL,
	[UserReservedReference] [char](15) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[UPCNumber] [char](13) NOT NULL,
	[AggregateSCCCodePI0] [char](14) NOT NULL,
	[UnitofMeasureUPC] [char](2) NOT NULL,
	[UnitofMeasureAggregateUPC] [char](2) NOT NULL,
	[UnitofMeasureSCCPI0] [char](2) NOT NULL,
	[UnitofMeasureSCCPI1] [char](2) NOT NULL,
	[UnitofMeasureSCCPI2] [char](2) NOT NULL,
	[UnitofMeasureSCCPI3] [char](2) NOT NULL,
	[UnitofMeasureSCCPI4] [char](2) NOT NULL,
	[UnitofMeasureSCCPI5] [char](2) NOT NULL,
	[UnitofMeasureSCCPI6] [char](2) NOT NULL,
	[UnitofMeasureSCCPI7] [char](2) NOT NULL,
	[UnitofMeasureSCCPI8] [char](2) NOT NULL,
	[IssueandReceipt] [char](1) NOT NULL,
	[ReplenishmentHoursStandard] [decimal](20, 7) NOT NULL,
	[ContainerCode] [char](5) NOT NULL,
	[ItemWeightRequiredYN] [char](1) NOT NULL,
	[Template] [char](20) NOT NULL,
	[Segment1] [char](10) NOT NULL,
	[Segment2] [char](10) NOT NULL,
	[Segment3] [char](10) NOT NULL,
	[Segment4] [char](10) NOT NULL,
	[Segment5] [char](10) NOT NULL,
	[Segment6] [char](10) NOT NULL,
	[Segment7] [char](10) NOT NULL,
	[Segment8] [char](10) NOT NULL,
	[Segment9] [char](10) NOT NULL,
	[Segment10] [char](10) NOT NULL,
	[MatrixControlled] [char](1) NOT NULL,
	[ActiveIngredientFlag] [char](1) NOT NULL,
	[BestBeforeDefaultDays] [int] NOT NULL,
	[CommitmentDateMethod] [char](1) NOT NULL,
	[LotExpiratonDateCalculationMet] [char](1) NOT NULL,
	[LotEffectiveDefaultDays] [int] NOT NULL,
	[PurchasingEffectiveDays] [int] NOT NULL,
	[SellByDefaultDays] [int] NOT NULL,
	[UserLotDate1DefaultDays] [int] NOT NULL,
	[UserLotDate2DefaultDays] [int] NOT NULL,
	[UserLotDate3DefaultDays] [int] NOT NULL,
	[UserLotDate4DefaultDays] [int] NOT NULL,
	[UserLotDate5DefaultDays] [int] NOT NULL,
	[DualTolerance] [decimal](20, 7) NOT NULL,
	[DualPickingProcessOption] [char](1) NOT NULL,
	[DualUnitOfMeasureItem] [char](1) NOT NULL,
	[CrossDockingFlag] [char](1) NOT NULL,
	[LotAuditFlag] [char](1) NOT NULL,
	[SpecialLotFormat] [char](1) NOT NULL,
	[RestrictWorkOrderLotAssignment] [char](1) NOT NULL,
	[LotNumberPreAssignment] [char](1) NOT NULL,
	[LotStatusCodeExpanded] [char](3) NOT NULL,
	[ConstraintsFlag] [char](1) NOT NULL,
	[APSPlanningUOM] [char](9) NOT NULL,
	[Consumable] [char](1) NOT NULL,
	[Composition] [char](1) NOT NULL,
	[PriorityOneAlertLevel] [decimal](20, 7) NOT NULL,
	[PriorityTwoAlertLevel] [decimal](20, 7) NOT NULL,
	[AllowShippingofHeldLots] [char](1) NOT NULL,
	[VendorManagedInventory] [char](1) NOT NULL,
	[MethodConfiguratorCosting] [char](1) NOT NULL,
	[ExplodeItem10] [char](1) NOT NULL,
	[OperationalThreshold] [decimal](20, 7) NOT NULL,
	[CumulativeThreshold] [decimal](20, 7) NOT NULL,
	[ThresholdUnitOfMeasure] [char](3) NOT NULL,
	[LeanManufacturingFlag] [char](1) NOT NULL,
	[LineCellIdentifier] [char](12) NOT NULL,
	[TotalProductCycleTime] [decimal](20, 7) NOT NULL,
	[KanbanItem] [char](1) NOT NULL,
	[DemandFlowEndItemFlag] [char](1) NOT NULL,
	[KanbanExplodeToLowerLevel] [char](1) NOT NULL,
	[SellableItem] [char](1) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEINItemMaster] PRIMARY KEY CLUSTERED 
(
	[ItemNumber] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEINItemMaster] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEINItemLocation]    Script Date: 5/8/13 12:13:23 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEINItemLocation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEINItemLocation](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[ItemNumber] [int] NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[Location] [char](20) NOT NULL,
	[LotNumber] [char](30) NOT NULL,
	[CompanyNumber] [char](5) NOT NULL,
	[PrimaryLocation] [char](1) NOT NULL,
	[GLCategory] [char](4) NOT NULL,
	[LotStatusCode] [char](1) NOT NULL,
	[LastReceiptDate] [datetime] NOT NULL,
	[QuantityOnHand] [decimal](22, 7) NOT NULL,
	[QuantityOnBackorder] [decimal](22, 7) NOT NULL,
	[QuantityOnPurchaseOrder] [decimal](22, 7) NOT NULL,
	[QuantityOnWorkOrderReceipt] [decimal](22, 7) NOT NULL,
	[QuantityOnSOOther1] [decimal](22, 7) NOT NULL,
	[QuantityOnSOOther2] [decimal](22, 7) NOT NULL,
	[QuantityOnPOOther1] [decimal](22, 7) NOT NULL,
	[QuantityOnHardCommit] [decimal](22, 7) NOT NULL,
	[QuantityOnSoftCommit] [decimal](22, 7) NOT NULL,
	[QuantityOnFutureCommit] [decimal](22, 7) NOT NULL,
	[QuantityOnWorkOrderSoftCommit] [decimal](22, 7) NOT NULL,
	[QuantityOnWorkOrderHardCommit] [decimal](22, 7) NOT NULL,
	[QuantityInTransit] [decimal](22, 7) NOT NULL,
	[QuantityInInspection] [decimal](22, 7) NOT NULL,
	[QuantityOnLoanToManufacturing] [decimal](22, 7) NOT NULL,
	[QuantityInbound] [decimal](22, 7) NOT NULL,
	[QuantityOutbound] [decimal](22, 7) NOT NULL,
	[NextCountDate] [datetime] NOT NULL,
	[FutureUseQty1] [decimal](15, 0) NOT NULL,
	[FutureUseQty2] [decimal](15, 0) NOT NULL,
	[UserReservedNumber] [int] NOT NULL,
	[UserReservedReference] [char](15) NOT NULL,
	[UserReservedAmount] [decimal](20, 7) NOT NULL,
	[UserReservedCode] [char](2) NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[UserID] [char](10) NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[UserReservedDate] [datetime] NOT NULL,
	[QuantityInOperation1] [decimal](22, 7) NOT NULL,
	[QuantityInOperation2] [decimal](22, 7) NOT NULL,
	[SecondaryQuantityHardCommitted] [decimal](22, 7) NOT NULL,
	[ProjectHardCommittedQtyPrimary] [decimal](22, 7) NOT NULL,
	[ProjectHardCommittedQtyinSecon] [decimal](22, 7) NOT NULL,
	[SecondaryQuantitySoftCommitted] [decimal](22, 7) NOT NULL,
	[SecondaryQuantityInboundWareh] [decimal](22, 7) NOT NULL,
	[SecondaryQuantityOutboundWare] [decimal](22, 7) NOT NULL,
	[QuantityonHandinSecondaryunits] [decimal](22, 7) NOT NULL,
	[SecondaryQuantityWorkOrderRcpt] [decimal](22, 7) NOT NULL,
	[QuantityonPurchaseOrderSecond] [decimal](22, 7) NOT NULL,
	[SecondaryQuantityWOHardCommit] [decimal](22, 7) NOT NULL,
	[SecondaryQuantityWOSoftCommit] [decimal](22, 7) NOT NULL,
	[CriticalHoldFlag] [char](1) NOT NULL,
	[WorkFlowPendingFlag] [char](1) NOT NULL,
	[ConfiguredStringID] [char](32) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEINItemLocation] PRIMARY KEY CLUSTERED 
(
	[ItemNumber] ASC,
	[BusinessUnitCode] ASC,
	[Location] ASC,
	[LotNumber] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEINItemLocation] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEINItemLedger]    Script Date: 5/8/13 12:13:23 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEINItemLedger]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEINItemLedger](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[NumberofLines] [int] NOT NULL,
	[ItemNumber] [int] NOT NULL,
	[ItemNumber02] [char](25) NOT NULL,
	[ItemNumber03] [char](25) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[Location] [char](20) NOT NULL,
	[LotNumber] [char](30) NOT NULL,
	[ParentLot] [char](30) NOT NULL,
	[StorageUnitNumber] [int] NOT NULL,
	[DetailSequenceNumber] [int] NOT NULL,
	[TransactionLineNumber] [decimal](20, 7) NOT NULL,
	[FromTo] [char](1) NOT NULL,
	[LotMasterCardex] [char](1) NOT NULL,
	[LotStatusCode] [char](1) NOT NULL,
	[LotPotency] [decimal](20, 7) NOT NULL,
	[LotGrade] [char](3) NOT NULL,
	[ParentItemNumber] [int] NOT NULL,
	[Branch] [char](12) NOT NULL,
	[ContractNumber] [char](12) NOT NULL,
	[ContractSupplement] [int] NOT NULL,
	[ContractBalancesUpdated] [char](1) NOT NULL,
	[DocumentCompany] [char](5) NOT NULL,
	[DocumentNumber] [int] NOT NULL,
	[DocumentType] [char](2) NOT NULL,
	[PayItem] [char](3) NOT NULL,
	[JournalEntryLineNumber] [decimal](20, 7) NOT NULL,
	[BatchNumber] [int] NOT NULL,
	[GLDate] [datetime] NOT NULL,
	[GLCategory] [char](4) NOT NULL,
	[OrderTypeCode] [char](2) NOT NULL,
	[OrderNumber] [int] NOT NULL,
	[OrderNumberDocumentCompany] [char](5) NOT NULL,
	[LineNumber] [decimal](20, 7) NOT NULL,
	[AsOfPostedCode] [char](1) NOT NULL,
	[TransactionDate] [datetime] NOT NULL,
	[TransactionUOM] [char](2) NOT NULL,
	[AddressNumber] [int] NOT NULL,
	[Explanation] [char](30) NOT NULL,
	[TransactionReference] [char](8) NOT NULL,
	[ReasonCode] [char](3) NOT NULL,
	[TransactionQuantity] [decimal](22, 7) NOT NULL,
	[UnitCost] [decimal](20, 7) NOT NULL,
	[ExtendedCostPrice] [decimal](20, 7) NOT NULL,
	[TerminalIdentification] [char](10) NOT NULL,
	[UniqueKeyIDInternal] [decimal](15, 0) NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[CreationDate] [datetime] NOT NULL,
	[AccountID] [char](8) NOT NULL,
	[SerialNumber] [char](25) NOT NULL,
	[BusinessUnitAlt] [char](12) NOT NULL,
	[ObjectAccount] [char](6) NOT NULL,
	[SubledgerGL] [char](8) NOT NULL,
	[Subsidiary] [char](8) NOT NULL,
	[UnitofMeasureSecondary] [char](2) NOT NULL,
	[CommingledOtherOwner] [char](1) NOT NULL,
	[ReverseorVoidRV] [char](1) NOT NULL,
	[SubledgerType] [char](1) NOT NULL,
	[UnitsSecondaryQuantityOrdered] [decimal](22, 7) NOT NULL,
	[ValuationPeriodEndingDate] [datetime] NOT NULL,
	[HistoricalDateJulian] [datetime] NOT NULL,
	[AddressNumberShipTo] [int] NOT NULL,
	[SequenceNumberOperations] [decimal](20, 7) NOT NULL,
	[RelatedFromLineNumber] [decimal](20, 7) NOT NULL,
	[TransactionGroupNumber] [decimal](20, 7) NOT NULL,
	[LotStatusCodeExpanded] [char](3) NOT NULL,
	[FutureUseDate] [datetime] NOT NULL,
	[LotStatusReasonCode] [char](3) NOT NULL,
	[SupplierLotNumber] [char](30) NOT NULL,
	[LicensePlateNumber] [char](40) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEINItemLedger] PRIMARY KEY CLUSTERED 
(
	[UniqueKeyIDInternal] ASC,
	[UserID] ASC,
	[CreationDate] ASC,
	[TimeOfDay] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEINItemLedger] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEINItemBranch]    Script Date: 5/8/13 12:13:23 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEINItemBranch]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEINItemBranch](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[ItemNumber] [int] NOT NULL,
	[ItemNumber02] [char](25) NOT NULL,
	[ItemNumber03] [char](25) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[SalesCategory01Code] [char](3) NOT NULL,
	[SalesCategory01] [char](30) NOT NULL,
	[SalesCategory02Code] [char](3) NOT NULL,
	[SalesCategory02] [char](30) NOT NULL,
	[SalesCategory03Code] [char](3) NOT NULL,
	[SalesCategory03] [char](30) NOT NULL,
	[SalesCategory04Code] [char](3) NOT NULL,
	[SalesCategory04] [char](30) NOT NULL,
	[SalesCategory05Code] [char](3) NOT NULL,
	[SalesCategory05] [char](30) NOT NULL,
	[SalesCategory06Code] [char](6) NOT NULL,
	[SalesCategory06] [char](30) NOT NULL,
	[SalesCategory07Code] [char](6) NOT NULL,
	[SalesCategory07] [char](30) NOT NULL,
	[SalesCategory08Code] [char](6) NOT NULL,
	[SalesCategory08] [char](30) NOT NULL,
	[SalesCategory09Code] [char](6) NOT NULL,
	[SalesCategory09] [char](30) NOT NULL,
	[SalesCategory10Code] [char](6) NOT NULL,
	[SalesCategory10] [char](30) NOT NULL,
	[PurchasingCategory01Code] [char](3) NOT NULL,
	[PurchasingCategory01] [char](30) NOT NULL,
	[PurchasingCategory02Code] [char](3) NOT NULL,
	[PurchasingCategory02] [char](30) NOT NULL,
	[PurchasingCategory03Code] [char](3) NOT NULL,
	[PurchasingCategory03] [char](30) NOT NULL,
	[PurchasingCategory04Code] [char](3) NOT NULL,
	[PurchasingCategory04] [char](30) NOT NULL,
	[PurchasingCategory05Code] [char](3) NOT NULL,
	[PurchasingCategory05] [char](30) NOT NULL,
	[PurchasingCategory06Code] [char](6) NOT NULL,
	[PurchasingCategory06] [char](30) NOT NULL,
	[PurchasingCategory07Code] [char](6) NOT NULL,
	[PurchasingCategory07] [char](30) NOT NULL,
	[PurchasingCategory08Code] [char](6) NOT NULL,
	[PurchasingCategory08] [char](30) NOT NULL,
	[PurchasingCategory09Code] [char](6) NOT NULL,
	[PurchasingCategory09] [char](30) NOT NULL,
	[PurchasingCategory10Code] [char](6) NOT NULL,
	[PurchasingCategory10] [char](30) NOT NULL,
	[CommodityCode] [char](15) NOT NULL,
	[ProductGroupCode] [char](3) NOT NULL,
	[ProductGroup] [char](30) NOT NULL,
	[DispatchGroup] [char](3) NOT NULL,
	[PrimaryLastSupplierNumber] [int] NOT NULL,
	[PlannerNumber] [int] NOT NULL,
	[BuyerNumber] [int] NOT NULL,
	[GLCategory] [char](4) NOT NULL,
	[CountryofOrigin] [char](3) NOT NULL,
	[ReorderPoint] [decimal](22, 7) NOT NULL,
	[ReorderQuantity] [decimal](22, 7) NOT NULL,
	[MaximumReorderQuantity] [decimal](22, 7) NOT NULL,
	[MinimumReorderQuantity] [decimal](22, 7) NOT NULL,
	[MultipleOrderQuantitySoPo] [int] NOT NULL,
	[ServiceLevel] [decimal](20, 7) NOT NULL,
	[SafetyStock] [decimal](22, 7) NOT NULL,
	[ShelfLifeDays] [int] NOT NULL,
	[CheckAvailability] [char](1) NOT NULL,
	[LayerCodeSource] [char](1) NOT NULL,
	[LotStatusCode] [char](1) NOT NULL,
	[PotencyControl] [char](1) NOT NULL,
	[GradeControl] [char](1) NOT NULL,
	[StandardPotency] [decimal](20, 7) NOT NULL,
	[FromPotency] [decimal](20, 7) NOT NULL,
	[ThruPotency] [decimal](20, 7) NOT NULL,
	[StandardGrade] [char](3) NOT NULL,
	[FromGrade] [char](3) NOT NULL,
	[ThruGrade] [char](3) NOT NULL,
	[ComponentType] [char](1) NOT NULL,
	[MarginMaintenance] [decimal](20, 7) NOT NULL,
	[ItemPriceGroupCode] [char](8) NOT NULL,
	[ItemPriceGroup] [char](30) NOT NULL,
	[BasketRepriceGroup] [char](8) NOT NULL,
	[OrderRepriceGroup] [char](8) NOT NULL,
	[BackOrdersAllowed] [char](1) NOT NULL,
	[ItemFlashMessage] [char](2) NOT NULL,
	[ABCCode1Sales] [char](1) NOT NULL,
	[ABCCode2Margin] [char](1) NOT NULL,
	[ABCCode3Investment] [char](1) NOT NULL,
	[ABCCodeOverrideIndicator] [char](1) NOT NULL,
	[ShippingCommodityClass] [char](3) NOT NULL,
	[PreferredCarrierSales] [int] NOT NULL,
	[PreferredCarrierPurchasing] [int] NOT NULL,
	[ShippingConditionsCode] [char](3) NOT NULL,
	[StockingTypeCode] [char](1) NOT NULL,
	[StockingType] [char](30) NOT NULL,
	[LineType] [char](2) NOT NULL,
	[FIFOProcessing] [char](1) NOT NULL,
	[CycleCountCategory] [char](3) NOT NULL,
	[PrintMessage] [char](10) NOT NULL,
	[TypeWarranty] [char](8) NOT NULL,
	[SerialNumberRequired] [char](1) NOT NULL,
	[PercentMargin] [decimal](20, 7) NOT NULL,
	[CommissionCategory] [char](8) NOT NULL,
	[ApplyFreight] [char](1) NOT NULL,
	[Taxable] [char](1) NOT NULL,
	[SalesTaxable] [char](1) NOT NULL,
	[PlanningCode] [char](1) NOT NULL,
	[ItemDisplayCode] [char](1) NOT NULL,
	[NetChangeFlag] [char](1) NOT NULL,
	[UnitsPerContainer] [decimal](15, 0) NOT NULL,
	[RoundToWholeNumber] [char](1) NOT NULL,
	[ItemRevisionLevel] [char](3) NOT NULL,
	[LeadtimeLevel] [int] NOT NULL,
	[LeadtimeManufacturing] [int] NOT NULL,
	[LeadtimeCumulative] [int] NOT NULL,
	[OrderPolicyCode] [char](1) NOT NULL,
	[ValueOrderPolicy] [decimal](15, 0) NOT NULL,
	[AccountingCostQuantity] [decimal](22, 7) NOT NULL,
	[MFGLeadtimeQuantity] [decimal](22, 7) NOT NULL,
	[LeadtimePerUnit] [decimal](20, 7) NOT NULL,
	[PlanningFenceRule] [char](1) NOT NULL,
	[FixedVariableLeadtime] [char](1) NOT NULL,
	[IssueTypeCode] [char](1) NOT NULL,
	[ECONumber] [char](12) NOT NULL,
	[ECOReason] [char](2) NOT NULL,
	[EngineeringChangeDate] [datetime] NOT NULL,
	[PlanningFence] [int] NOT NULL,
	[FreezeFence] [int] NOT NULL,
	[MessageDisplayFence] [int] NOT NULL,
	[TimeFence] [int] NOT NULL,
	[ShipmentLeadtimeOffset] [int] NOT NULL,
	[MoveHours] [decimal](20, 7) NOT NULL,
	[QueueHours] [decimal](20, 7) NOT NULL,
	[StandardSetupHours] [decimal](20, 7) NOT NULL,
	[ShrinkFactor] [decimal](20, 7) NOT NULL,
	[ShrinkFactorMethod] [char](1) NOT NULL,
	[TimeBasis] [char](1) NOT NULL,
	[BatchQuantity] [decimal](22, 7) NOT NULL,
	[OrderWith] [char](1) NOT NULL,
	[ExpediteDamperDays] [int] NOT NULL,
	[DeferDamperDays] [int] NOT NULL,
	[MultipleOrderQuantityMRP] [decimal](22, 7) NOT NULL,
	[SafetyLeadtime] [int] NOT NULL,
	[MakeBuyCode] [char](1) NOT NULL,
	[DateFutureUse] [datetime] NOT NULL,
	[LowLevelCode] [int] NOT NULL,
	[CommitmentMethod] [char](1) NOT NULL,
	[UserReservedCode] [char](2) NOT NULL,
	[UserReservedDate] [datetime] NOT NULL,
	[UserReservedAmount] [decimal](20, 7) NOT NULL,
	[UserReservedNumber] [int] NOT NULL,
	[UserReservedReference] [char](15) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[TempFlashMessage] [char](2) NOT NULL,
	[SpecificCommitmentDays] [int] NOT NULL,
	[ReplenishmentHoursStandard] [decimal](20, 7) NOT NULL,
	[IssueandReceipt] [char](1) NOT NULL,
	[ActiveIngredientFlag] [char](1) NOT NULL,
	[BestBeforeDefaultDays] [int] NOT NULL,
	[CommitmentDateMethod] [char](1) NOT NULL,
	[LotExpiratonDateCalculationMet] [char](1) NOT NULL,
	[LotEffectiveDefaultDays] [int] NOT NULL,
	[MixDatesLotsYN] [char](1) NOT NULL,
	[PurchasingEffectiveDays] [int] NOT NULL,
	[SellByDefaultDays] [int] NOT NULL,
	[UserLotDate1DefaultDays] [int] NOT NULL,
	[UserLotDate2DefaultDays] [int] NOT NULL,
	[UserLotDate3DefaultDays] [int] NOT NULL,
	[UserLotDate4DefaultDays] [int] NOT NULL,
	[UserLotDate5DefaultDays] [int] NOT NULL,
	[CrossDockingFlag] [char](1) NOT NULL,
	[LotAuditFlag] [char](1) NOT NULL,
	[SpecialLotFormat] [char](1) NOT NULL,
	[RestrictWorkOrderLotAssignment] [char](1) NOT NULL,
	[LotNumberPreAssignment] [char](1) NOT NULL,
	[LotStatusCodeExpanded] [char](3) NOT NULL,
	[ConstraintsFlag] [char](1) NOT NULL,
	[PriorityOneAlertLevel] [int] NOT NULL,
	[PriorityTwoAlertLevel] [int] NOT NULL,
	[LeadtimeConversionFactor] [decimal](20, 7) NOT NULL,
	[AllowShippingofHeldLots] [char](1) NOT NULL,
	[OperationalThreshold] [decimal](20, 7) NOT NULL,
	[CumulativeThreshold] [decimal](20, 7) NOT NULL,
	[ThresholdUnitOfMeasure] [char](3) NOT NULL,
	[LeanManufacturingFlag] [char](1) NOT NULL,
	[LineCellIdentifier] [char](12) NOT NULL,
	[TotalProductCycleTime] [decimal](20, 7) NOT NULL,
	[KanbanItem] [char](1) NOT NULL,
	[DemandFlowEndItemFlag] [char](1) NOT NULL,
	[KanbanExplodeToLowerLevel] [char](1) NOT NULL,
	[SellableItem] [char](1) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEINItemBranch] PRIMARY KEY CLUSTERED 
(
	[ItemNumber] ASC,
	[BusinessUnitCode] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEINItemBranch] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEINCostLedger]    Script Date: 5/8/13 12:13:24 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEINCostLedger]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEINCostLedger](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[ItemNumber] [int] NOT NULL,
	[ItemNumber02] [char](25) NOT NULL,
	[ItemNumber03] [char](25) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[Location] [char](20) NOT NULL,
	[LotNumber] [char](30) NOT NULL,
	[LotGrade] [char](3) NOT NULL,
	[CostMethodCode] [char](2) NOT NULL,
	[UnitCost] [decimal](20, 7) NOT NULL,
	[PurchasingCostingSelection] [char](1) NOT NULL,
	[InventoryCostingSelection] [char](1) NOT NULL,
	[UserReservedCode] [char](2) NOT NULL,
	[UserReservedDate] [datetime] NOT NULL,
	[UserReservedAmount] [decimal](20, 7) NOT NULL,
	[UserReservedNumber] [int] NOT NULL,
	[UserReservedReference] [char](15) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[CostChangedFlag] [char](2) NOT NULL,
	[CarryingCost] [int] NOT NULL,
	[OverstockCost] [int] NOT NULL,
	[StockoutCost] [int] NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEINCostLedger] PRIMARY KEY CLUSTERED 
(
	[ItemNumber] ASC,
	[BusinessUnitCode] ASC,
	[Location] ASC,
	[LotNumber] ASC,
	[CostMethodCode] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEINCostLedger] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEINBranchPlantConstants]    Script Date: 5/8/13 12:13:24 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEINBranchPlantConstants]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEINBranchPlantConstants](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[InstallSystemCode] [char](4) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[GeneralLedgerExplanation] [char](1) NOT NULL,
	[SymbolToIdentifyShortInvNo] [char](1) NOT NULL,
	[SymbolToIdentifyLongInvNo] [char](1) NOT NULL,
	[SymbolToIdentify3rdInvNo] [char](1) NOT NULL,
	[SymbolToIdentifyCustomerNo] [char](1) NOT NULL,
	[ConfiguratorSegmentDelimiter] [char](1) NOT NULL,
	[LocationSeparatorcharacter] [char](1) NOT NULL,
	[NumberofcharactersAisle] [int] NOT NULL,
	[NumberofcharactersBin] [int] NOT NULL,
	[NumberofcharactersCode03] [int] NOT NULL,
	[NumberofcharactersCode04] [int] NOT NULL,
	[NumberofcharactersCode05] [int] NOT NULL,
	[NumberofcharactersCode06] [int] NOT NULL,
	[NumberofcharactersCode07] [int] NOT NULL,
	[NumberofcharactersCode08] [int] NOT NULL,
	[NumberofcharactersCode09] [int] NOT NULL,
	[NumberofcharactersCode10] [int] NOT NULL,
	[JustifyAisle] [char](1) NOT NULL,
	[JustifyBin] [char](1) NOT NULL,
	[JustifyCode03] [char](1) NOT NULL,
	[JustifyCode04] [char](1) NOT NULL,
	[JustifyCode05] [char](1) NOT NULL,
	[JustifyCode06] [char](1) NOT NULL,
	[JustifyCode07] [char](1) NOT NULL,
	[JustifyCode08] [char](1) NOT NULL,
	[JustifyCode09] [char](1) NOT NULL,
	[JustifyCode10] [char](1) NOT NULL,
	[AddressNumber] [int] NOT NULL,
	[PurchaseOrderIssueCost] [decimal](20, 7) NOT NULL,
	[InventoryCarryingCost] [decimal](20, 7) NOT NULL,
	[LeadtimeWeightFactor] [decimal](20, 7) NOT NULL,
	[NumberOfDaysInYear] [int] NOT NULL,
	[ABCCode1Sales] [decimal](20, 7) NOT NULL,
	[ABCCode1GrossMargin] [decimal](20, 7) NOT NULL,
	[ABCCode1AverageInvestment] [decimal](20, 7) NOT NULL,
	[ABCCode2Sales] [decimal](20, 7) NOT NULL,
	[ABCCode2GrossMargin] [decimal](20, 7) NOT NULL,
	[ABCCode2AverageInvestment] [decimal](20, 7) NOT NULL,
	[ABCCode3Sales] [decimal](20, 7) NOT NULL,
	[ABCCode3GrossMargin] [decimal](20, 7) NOT NULL,
	[ABCCode3AverageInvestment] [decimal](20, 7) NOT NULL,
	[CurrentPeriod] [int] NOT NULL,
	[InterfaceGL] [char](1) NOT NULL,
	[WriteUnitstoJournalEntries] [char](1) NOT NULL,
	[CommitmentMethod] [char](1) NOT NULL,
	[SalesCostingMethod] [char](2) NOT NULL,
	[PurchasingCostingMethod] [char](2) NOT NULL,
	[BackOrdersAllowed] [char](1) NOT NULL,
	[SpecificCommitmentDays] [int] NOT NULL,
	[BatchControlRequired] [char](1) NOT NULL,
	[ManagerApprovalOfInput] [char](1) NOT NULL,
	[MatchType] [char](1) NOT NULL,
	[CrossReferenceTypeCode1] [char](2) NOT NULL,
	[CrossReferenceTypeCode2] [char](2) NOT NULL,
	[ApprovalRouteCode] [char](12) NOT NULL,
	[QuantitySoftCommittedToSO] [char](1) NOT NULL,
	[QuantityHardCommittedToSO] [char](1) NOT NULL,
	[QuantityFutureCommittedToSO] [char](1) NOT NULL,
	[QuantityHardCommittedToWO] [char](1) NOT NULL,
	[OtherQuantity1SO] [char](1) NOT NULL,
	[OtherQuantity2SO] [char](1) NOT NULL,
	[QuantityOnHold] [char](1) NOT NULL,
	[QuantityOnPOReceipts] [char](1) NOT NULL,
	[QuantityOnWOReceipts] [char](1) NOT NULL,
	[OtherQuantity1PO] [char](1) NOT NULL,
	[QuantityOnSafetyStock] [char](1) NOT NULL,
	[QuantityInInspection] [char](1) NOT NULL,
	[QuantityInTransit] [char](1) NOT NULL,
	[QuantityInOperation1] [char](1) NOT NULL,
	[QuantityInOperation2] [char](1) NOT NULL,
	[QuantityOnLoanToManufacturing] [char](1) NOT NULL,
	[UpdateLastInCost] [char](1) NOT NULL,
	[DimensionUnitOfMeasure] [char](2) NOT NULL,
	[VolumeDisplayedUOM] [char](2) NOT NULL,
	[UnitOfMeasureWeight] [char](2) NOT NULL,
	[AllowDuplicateLots] [char](1) NOT NULL,
	[LocationControl] [char](1) NOT NULL,
	[WarehouseControl] [char](1) NOT NULL,
	[InclusionVersion] [char](3) NOT NULL,
	[ShippingLocation] [char](20) NOT NULL,
	[ReceivingLocation] [char](20) NOT NULL,
	[TemperatureType] [char](1) NOT NULL,
	[DensityType] [char](1) NOT NULL,
	[StandardTemperature] [decimal](20, 7) NOT NULL,
	[USorMetricMeasurement] [char](1) NOT NULL,
	[PotencyControl] [char](1) NOT NULL,
	[GradeControl] [char](1) NOT NULL,
	[ForeignDepot] [char](1) NOT NULL,
	[QualityControl] [char](1) NOT NULL,
	[FutureUse] [char](1) NOT NULL,
	[USIncrementsDelimeter] [char](1) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[InventoryLotCreationYN] [char](1) NOT NULL,
	[LocationSegmentControlYNInv] [char](1) NOT NULL,
	[SeparatorSegment] [char](1) NOT NULL,
	[SymboltoIdentifySegmentedItem] [char](1) NOT NULL,
	[LotAuditFlag] [char](1) NOT NULL,
	[SpecialLotFormat] [char](1) NOT NULL,
	[RestrictWorkOrderLotAssignment] [char](1) NOT NULL,
	[LotNumberPreAssignment] [char](1) NOT NULL,
	[BranchCountryOfOriginCode] [char](3) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEINBranchPlantConstants] PRIMARY KEY CLUSTERED 
(
	[InstallSystemCode] ASC,
	[BusinessUnitCode] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEINBranchPlantConstants] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEIBDistributionMFGAAIValue]    Script Date: 5/8/13 12:13:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEIBDistributionMFGAAIValue]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEIBDistributionMFGAAIValue](
	[SourceID] [int] NOT NULL,
	[Source] [nchar](20) NOT NULL,
	[NumberAAITableNumber] [int] NOT NULL,
	[CompanyNumber] [nchar](5) NOT NULL,
	[OrderTypeCode] [nchar](2) NOT NULL,
	[DocumentType] [nchar](2) NOT NULL,
	[GLCategory] [nchar](4) NOT NULL,
	[CostType] [nchar](3) NOT NULL,
	[BusinessUnitCode] [nchar](12) NOT NULL,
	[ObjectAccount] [nchar](6) NOT NULL,
	[Subsidiary] [nchar](8) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEIBDistributionManufacturingAAIValues] PRIMARY KEY CLUSTERED 
(
	[NumberAAITableNumber] ASC,
	[CompanyNumber] ASC,
	[OrderTypeCode] ASC,
	[DocumentType] ASC,
	[GLCategory] ASC,
	[CostType] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
ALTER AUTHORIZATION ON [dbo].[JDEIBDistributionMFGAAIValue] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEGSCompanyMaster]    Script Date: 5/8/13 12:13:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEGSCompanyMaster]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEGSCompanyMaster](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[CompanyNumber] [char](5) NOT NULL,
	[CompanyName] [char](30) NOT NULL,
	[AlternateCompanyName] [char](40) NOT NULL,
	[DateFiscalYearBegins] [datetime] NOT NULL,
	[CurrentPeriod] [int] NOT NULL,
	[AllowMultiCurrIntercoJEsYN] [char](1) NOT NULL,
	[MultiCurrencyConversion] [char](1) NOT NULL,
	[SearchTypeSecurityYN] [char](1) NOT NULL,
	[ComputationID] [char](1) NOT NULL,
	[DefaultAssetBU] [char](1) NOT NULL,
	[DefaultDepreciationBU] [char](1) NOT NULL,
	[DefaultAccumDepreciationBU] [char](1) NOT NULL,
	[DefaultRevenueBillingBU] [char](1) NOT NULL,
	[SymbolForStructuredCode] [char](1) NOT NULL,
	[BookForIncomeTax] [char](1) NOT NULL,
	[TaxYearBeginingPeriod] [int] NOT NULL,
	[TaxYearBeginingPeriodOld] [int] NOT NULL,
	[NewTaxYearEnd] [datetime] NOT NULL,
	[GLInterfaceYN] [char](1) NOT NULL,
	[StructuredAccountCodeYN] [char](1) NOT NULL,
	[NormalNumberOfPeriods] [char](2) NOT NULL,
	[FiscalDatePattern] [char](1) NOT NULL,
	[FinancialReportingPeriod] [int] NOT NULL,
	[FinancialReportingYear] [int] NOT NULL,
	[CurrencyCode] [char](3) NOT NULL,
	[SymbolForItemNumber] [char](1) NOT NULL,
	[SymbolForUnitTag] [char](1) NOT NULL,
	[SymbolForSerialTag] [char](1) NOT NULL,
	[DelinquencyNotice] [char](1) NOT NULL,
	[PrintStatements] [char](1) NOT NULL,
	[AutoCash] [char](1) NOT NULL,
	[AutoCashAlgorithm] [char](2) NOT NULL,
	[AgingMethod] [char](1) NOT NULL,
	[CurrentAgingDays] [int] NOT NULL,
	[AgingDays01] [int] NOT NULL,
	[AgingDays02] [int] NOT NULL,
	[AgingDays03] [int] NOT NULL,
	[AgingDays04] [int] NOT NULL,
	[AgingDays05] [int] NOT NULL,
	[AgingDays06] [int] NOT NULL,
	[AgingDays07] [int] NOT NULL,
	[FiftyTwoPeriodFinancialYear] [int] NOT NULL,
	[FiftyTwoPeriodFinancialPeriod] [int] NOT NULL,
	[FiftyTwoPeriodNormalNumPeriods] [int] NOT NULL,
	[PercentageFactor] [decimal](20, 7) NOT NULL,
	[AgingDate] [char](1) NOT NULL,
	[AgeAsOfDate] [datetime] NOT NULL,
	[CurrentPeriodAR] [int] NOT NULL,
	[CurrentPeriodAP] [int] NOT NULL,
	[BeginingFiscalYearAR] [datetime] NOT NULL,
	[BeginingFiscalYearAP] [datetime] NOT NULL,
	[AddressNumber] [int] NOT NULL,
	[SignatureBlock] [char](40) NOT NULL,
	[PrintCompanyName] [char](1) NOT NULL,
	[FutureUse01] [char](1) NOT NULL,
	[FutureUse02] [char](1) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[LastTimeUpdated] [int] NOT NULL,
	[TargetSystemIdentifier] [int] NOT NULL,
	[TargetCompany] [char](5) NOT NULL,
	[SourceAliasSystem] [char](10) NOT NULL,
	[TargetAddressNumber] [int] NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEGSCompanyMaster] PRIMARY KEY CLUSTERED 
(
	[CompanyNumber] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEGSCompanyMaster] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEGSBusinessUnitMaster]    Script Date: 5/8/13 12:13:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEGSBusinessUnitMaster]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEGSBusinessUnitMaster](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[Type] [char](2) NOT NULL,
	[BusinessUnitTypeDescription] [char](30) NOT NULL,
	[DescriptionCompressed] [char](40) NOT NULL,
	[LevelOfDetail] [char](1) NOT NULL,
	[CompanyNumber] [char](5) NOT NULL,
	[AddressNumber] [int] NOT NULL,
	[OwnerReceivableAddress] [int] NOT NULL,
	[County] [char](3) NOT NULL,
	[StateCode] [char](3) NOT NULL,
	[ModelAccountConsolidations] [char](1) NOT NULL,
	[Description01] [char](30) NOT NULL,
	[Description02] [char](30) NOT NULL,
	[Description03] [char](30) NOT NULL,
	[Description04] [char](30) NOT NULL,
	[Category01Code] [char](3) NOT NULL,
	[Category01] [char](30) NOT NULL,
	[Category02Code] [char](3) NOT NULL,
	[Category02] [char](30) NOT NULL,
	[Category03Code] [char](3) NOT NULL,
	[Category03] [char](30) NOT NULL,
	[Category04Code] [char](3) NOT NULL,
	[Category04] [char](30) NOT NULL,
	[Category05Code] [char](3) NOT NULL,
	[Category05] [char](30) NOT NULL,
	[Category06Code] [char](3) NOT NULL,
	[Category06] [char](30) NOT NULL,
	[Category07Code] [char](3) NOT NULL,
	[Category07] [char](30) NOT NULL,
	[Category08Code] [char](3) NOT NULL,
	[Category08] [char](30) NOT NULL,
	[Category09Code] [char](3) NOT NULL,
	[Category09] [char](30) NOT NULL,
	[Category10Code] [char](3) NOT NULL,
	[Category10] [char](30) NOT NULL,
	[Category11Code] [char](3) NOT NULL,
	[Category11] [char](30) NOT NULL,
	[Category12Code] [char](3) NOT NULL,
	[Category12] [char](30) NOT NULL,
	[Category13Code] [char](3) NOT NULL,
	[Category13] [char](30) NOT NULL,
	[Category14Code] [char](3) NOT NULL,
	[Category14] [char](30) NOT NULL,
	[Category15Code] [char](3) NOT NULL,
	[Category15] [char](30) NOT NULL,
	[Category16Code] [char](3) NOT NULL,
	[Category16] [char](30) NOT NULL,
	[Category17Code] [char](3) NOT NULL,
	[Category17] [char](30) NOT NULL,
	[Category18Code] [char](3) NOT NULL,
	[Category18] [char](30) NOT NULL,
	[Category19Code] [char](3) NOT NULL,
	[Category19] [char](30) NOT NULL,
	[Category20Code] [char](3) NOT NULL,
	[Category20] [char](30) NOT NULL,
	[Category21Code] [char](10) NOT NULL,
	[Category21] [char](30) NOT NULL,
	[Category22Code] [char](10) NOT NULL,
	[Category22] [char](30) NOT NULL,
	[Category23Code] [char](10) NOT NULL,
	[Category23] [char](30) NOT NULL,
	[Category24Code] [char](10) NOT NULL,
	[Category24] [char](30) NOT NULL,
	[Category25Code] [char](10) NOT NULL,
	[Category25] [char](30) NOT NULL,
	[Category26Code] [char](10) NOT NULL,
	[Category26] [char](30) NOT NULL,
	[Category27Code] [char](10) NOT NULL,
	[Category27] [char](30) NOT NULL,
	[Category28Code] [char](10) NOT NULL,
	[Category28] [char](30) NOT NULL,
	[Category29Code] [char](10) NOT NULL,
	[Category29] [char](30) NOT NULL,
	[Category30Code] [char](10) NOT NULL,
	[Category30] [char](30) NOT NULL,
	[TaxArea] [char](10) NOT NULL,
	[TaxEntity] [int] NOT NULL,
	[TaxRateArea] [char](10) NOT NULL,
	[TaxExplanationCode] [char](2) NOT NULL,
	[TaxDeduciton01Code] [char](4) NOT NULL,
	[TaxDeduciton02Code] [char](4) NOT NULL,
	[TaxDeduciton03Code] [char](4) NOT NULL,
	[TaxDeduciton04Code] [char](4) NOT NULL,
	[TaxDeduciton05Code] [char](4) NOT NULL,
	[TaxDeduciton06Code] [char](4) NOT NULL,
	[TaxDeduciton07Code] [char](4) NOT NULL,
	[TaxDeduciton08Code] [char](4) NOT NULL,
	[TaxDeduciton09Code] [char](4) NOT NULL,
	[TaxDeduciton10Code] [char](4) NOT NULL,
	[TaxDistributableYN01] [char](1) NOT NULL,
	[TaxDistributableYN02] [char](1) NOT NULL,
	[TaxDistributableYN03] [char](1) NOT NULL,
	[TaxDistributableYN04] [char](1) NOT NULL,
	[TaxDistributableYN05] [char](1) NOT NULL,
	[TaxDistributableYN06] [char](1) NOT NULL,
	[TaxDistributableYN07] [char](1) NOT NULL,
	[TaxDistributableYN08] [char](1) NOT NULL,
	[TaxDistributableYN09] [char](1) NOT NULL,
	[TaxDistributableYN10] [char](1) NOT NULL,
	[ComputeStatusCode01] [char](1) NOT NULL,
	[ComputeStatusCode02] [char](1) NOT NULL,
	[ComputeStatusCode03] [char](1) NOT NULL,
	[ComputeStatusCode04] [char](1) NOT NULL,
	[ComputeStatusCode05] [char](1) NOT NULL,
	[ComputeStatusCode06] [char](1) NOT NULL,
	[ComputeStatusCode07] [char](1) NOT NULL,
	[ComputeStatusCode08] [char](1) NOT NULL,
	[ComputeStatusCode09] [char](1) NOT NULL,
	[ComputeStatusCode10] [char](1) NOT NULL,
	[PostingEditCode] [char](1) NOT NULL,
	[PostingEditCodeDescription] [char](30) NOT NULL,
	[SummarizationMethod] [char](1) NOT NULL,
	[InvoiceStatementSummarization] [char](1) NOT NULL,
	[GLBankAccount] [char](8) NOT NULL,
	[AllocationLevel] [char](2) NOT NULL,
	[LaborDistributionMethod] [char](1) NOT NULL,
	[LaborDistributionMultiplier] [decimal](20, 7) NOT NULL,
	[LaborAccount] [char](6) NOT NULL,
	[PremiumAccount] [char](6) NOT NULL,
	[BurdenAccount] [char](6) NOT NULL,
	[SubsidiaryAccount] [char](8) NOT NULL,
	[TotalUnits] [decimal](20, 7) NOT NULL,
	[SubledgerInactiveCode] [char](1) NOT NULL,
	[Supervisor] [int] NOT NULL,
	[ContractType] [char](4) NOT NULL,
	[CeritifedJobYN] [char](1) NOT NULL,
	[ProjectNumber] [char](12) NOT NULL,
	[BillingType] [char](1) NOT NULL,
	[PercentComplete] [decimal](20, 7) NOT NULL,
	[PercentCompleteAggregateDetail] [decimal](20, 7) NOT NULL,
	[CostToComplete] [decimal](20, 7) NOT NULL,
	[InterestComputationCode] [char](4) NOT NULL,
	[InterestComputationCodeLateRev] [char](4) NOT NULL,
	[PlannedStartDate] [datetime] NOT NULL,
	[ActualStartDate] [datetime] NOT NULL,
	[PlannedCompletionDate] [datetime] NOT NULL,
	[ActualCompletionDate] [datetime] NOT NULL,
	[OtherDate05] [datetime] NOT NULL,
	[OtherDate06] [datetime] NOT NULL,
	[FinalPaymentDate] [datetime] NOT NULL,
	[CostAtCompletion] [decimal](20, 7) NOT NULL,
	[ProfitAtCompletion] [decimal](20, 7) NOT NULL,
	[EEOCodeYN] [char](1) NOT NULL,
	[EquipmentRateCode] [char](2) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[BranchType] [char](15) NOT NULL,
	[APSBusinessUnit] [char](10) NOT NULL,
	[TargetBusinessUnit] [char](12) NOT NULL,
	[LastTimeUpdated] [int] NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEGSBusinessUnitMaster] PRIMARY KEY CLUSTERED 
(
	[BusinessUnitCode] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEGSBusinessUnitMaster] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEGSBatchControlRecords]    Script Date: 5/8/13 12:13:26 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEGSBatchControlRecords]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEGSBatchControlRecords](
	[SourceID] [int] NOT NULL,
	[Source] [nchar](20) NOT NULL,
	[BatchType] [nchar](2) NOT NULL,
	[BatchNumber] [int] NOT NULL,
	[BatchStatus] [nchar](1) NOT NULL,
	[BatchApprovedforPosting] [nchar](1) NOT NULL,
	[InputTotal] [decimal](20, 7) NOT NULL,
	[UserID] [nchar](10) NOT NULL,
	[BatchDate] [datetime] NOT NULL,
	[AmountNumberDocumentExpected] [int] NOT NULL,
	[BalancedDocumentsandAmounts] [nchar](1) NOT NULL,
	[BalancedJE] [nchar](1) NOT NULL,
	[AmountEntered] [decimal](20, 7) NOT NULL,
	[AmountDocumentsEntered] [decimal](20, 7) NOT NULL,
	[AuthorizedUserID] [nchar](10) NOT NULL,
	[PostOutofBalance] [nchar](1) NOT NULL,
	[IncludeBatchonIntegrityflag] [nchar](1) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeUpdated] [int] NOT NULL,
	[ProgramID] [nchar](10) NOT NULL,
	[WorkStationID] [nchar](10) NOT NULL,
	[AutoOffsetMode] [nchar](1) NOT NULL,
	[AmountInputTotal] [decimal](20, 7) NOT NULL,
	[DetailedRestatementProcessed] [nchar](1) NOT NULL,
	[CashBasisProcessed] [nchar](1) NOT NULL,
	[52PeriodProcessed] [nchar](1) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEGSBatchControlRecords] PRIMARY KEY CLUSTERED 
(
	[BatchType] ASC,
	[BatchNumber] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
ALTER AUTHORIZATION ON [dbo].[JDEGSBatchControlRecords] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEGSAccountFiscalDatePatterns]    Script Date: 5/8/13 12:13:26 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEGSAccountFiscalDatePatterns]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEGSAccountFiscalDatePatterns](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[FiscalDatePattern] [char](1) NOT NULL,
	[FiscalYear] [int] NOT NULL,
	[DateFiscalYearBegins] [datetime] NOT NULL,
	[FiscalQuarter] [char](4) NOT NULL,
	[EndOfPeriod01] [datetime] NOT NULL,
	[EndOfPeriod02] [datetime] NOT NULL,
	[EndOfPeriod03] [datetime] NOT NULL,
	[EndOfPeriod04] [datetime] NOT NULL,
	[EndOfPeriod05] [datetime] NOT NULL,
	[EndOfPeriod06] [datetime] NOT NULL,
	[EndOfPeriod07] [datetime] NOT NULL,
	[EndOfPeriod08] [datetime] NOT NULL,
	[EndOfPeriod09] [datetime] NOT NULL,
	[EndOfPeriod10] [datetime] NOT NULL,
	[EndOfPeriod11] [datetime] NOT NULL,
	[EndOfPeriod12] [datetime] NOT NULL,
	[EndOfPeriod13] [datetime] NOT NULL,
	[EndOfPeriod14] [datetime] NOT NULL,
	[DatePatternType] [char](1) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[LastTimeUpdated] [int] NOT NULL,
	[Century] [int] NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEGSAccountFiscalDatePatterns] PRIMARY KEY CLUSTERED 
(
	[FiscalDatePattern] ASC,
	[DateFiscalYearBegins] ASC,
	[FiscalQuarter] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEGSAccountFiscalDatePatterns] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEGAAccountMaster]    Script Date: 5/8/13 12:13:26 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEGAAccountMaster]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEGAAccountMaster](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[CompanyNumber] [char](5) NOT NULL,
	[AccountID] [char](8) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[Object] [char](6) NOT NULL,
	[Subsidiary] [char](8) NOT NULL,
	[FlexAccount] [char](25) NOT NULL,
	[Description01] [char](30) NOT NULL,
	[AccountLevelOfDetail] [char](1) NOT NULL,
	[BudgetPatternCode] [char](3) NOT NULL,
	[PostingEditCode] [char](1) NOT NULL,
	[Billable] [char](1) NOT NULL,
	[CurrencyCode] [char](3) NOT NULL,
	[UnitOfMeasure] [char](2) NOT NULL,
	[Category01Code] [char](3) NOT NULL,
	[Category01] [char](30) NOT NULL,
	[Category02Code] [char](3) NOT NULL,
	[Category02] [char](30) NOT NULL,
	[Category03Code] [char](3) NOT NULL,
	[Category03] [char](30) NOT NULL,
	[Category04Code] [char](3) NOT NULL,
	[Category04] [char](30) NOT NULL,
	[Category05Code] [char](3) NOT NULL,
	[Category05] [char](30) NOT NULL,
	[Category06Code] [char](3) NOT NULL,
	[Category06] [char](30) NOT NULL,
	[Category07Code] [char](3) NOT NULL,
	[Category07] [char](30) NOT NULL,
	[Category08Code] [char](3) NOT NULL,
	[Category08] [char](30) NOT NULL,
	[Category09Code] [char](3) NOT NULL,
	[Category09] [char](30) NOT NULL,
	[Category10Code] [char](3) NOT NULL,
	[Category10] [char](30) NOT NULL,
	[Category11Code] [char](3) NOT NULL,
	[Category11] [char](30) NOT NULL,
	[Category12Code] [char](3) NOT NULL,
	[Category12] [char](30) NOT NULL,
	[Category13Code] [char](3) NOT NULL,
	[Category13] [char](30) NOT NULL,
	[Category14Code] [char](3) NOT NULL,
	[Category14] [char](30) NOT NULL,
	[Category15Code] [char](3) NOT NULL,
	[Category15] [char](30) NOT NULL,
	[Category16Code] [char](3) NOT NULL,
	[Category16] [char](30) NOT NULL,
	[Category17Code] [char](3) NOT NULL,
	[Category17] [char](30) NOT NULL,
	[Category18Code] [char](3) NOT NULL,
	[Category18] [char](30) NOT NULL,
	[Category19Code] [char](3) NOT NULL,
	[Category19] [char](30) NOT NULL,
	[Category20Code] [char](3) NOT NULL,
	[Category20] [char](30) NOT NULL,
	[Category21Code] [char](10) NOT NULL,
	[Category21] [char](30) NOT NULL,
	[Category22Code] [char](10) NOT NULL,
	[Category22] [char](30) NOT NULL,
	[Category23Code] [char](10) NOT NULL,
	[Category23] [char](30) NOT NULL,
	[Category24Code] [char](10) NOT NULL,
	[Category24] [char](30) NOT NULL,
	[Category25Code] [char](10) NOT NULL,
	[Category25] [char](30) NOT NULL,
	[Category26Code] [char](10) NOT NULL,
	[Category26] [char](30) NOT NULL,
	[Category27Code] [char](10) NOT NULL,
	[Category27] [char](30) NOT NULL,
	[Category28Code] [char](10) NOT NULL,
	[Category28] [char](30) NOT NULL,
	[Category29Code] [char](10) NOT NULL,
	[Category29] [char](30) NOT NULL,
	[Category30Code] [char](10) NOT NULL,
	[Category30] [char](30) NOT NULL,
	[Category31Code] [char](10) NOT NULL,
	[Category31] [char](30) NOT NULL,
	[Category32Code] [char](10) NOT NULL,
	[Category32] [char](30) NOT NULL,
	[Category33Code] [char](10) NOT NULL,
	[Category33] [char](30) NOT NULL,
	[Category34Code] [char](10) NOT NULL,
	[Category34] [char](30) NOT NULL,
	[Category35Code] [char](10) NOT NULL,
	[Category35] [char](30) NOT NULL,
	[Category36Code] [char](10) NOT NULL,
	[Category36] [char](30) NOT NULL,
	[Category37Code] [char](10) NOT NULL,
	[Category37] [char](30) NOT NULL,
	[Category38Code] [char](10) NOT NULL,
	[Category38] [char](30) NOT NULL,
	[Category39Code] [char](10) NOT NULL,
	[Category39] [char](30) NOT NULL,
	[Category40Code] [char](10) NOT NULL,
	[Category40] [char](30) NOT NULL,
	[Category41Code] [char](10) NOT NULL,
	[Category41] [char](30) NOT NULL,
	[Category42Code] [char](10) NOT NULL,
	[Category42] [char](30) NOT NULL,
	[Category43Code] [char](10) NOT NULL,
	[Category43] [char](30) NOT NULL,
	[AlternateObject] [char](6) NOT NULL,
	[AlternateSubsidiary] [char](8) NOT NULL,
	[WorkersComp] [char](4) NOT NULL,
	[MethodOfComputation] [char](1) NOT NULL,
	[EquipmentRateCode] [char](2) NOT NULL,
	[HeaderTypeCode] [char](1) NOT NULL,
	[LevelOfDetailQuantityRollUp] [char](1) NOT NULL,
	[CostCodeComplete] [char](1) NOT NULL,
	[ModelAccountConsolidations] [char](1) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[LastTimeUpdated] [int] NOT NULL,
	[CostObjectEditCode01] [char](1) NOT NULL,
	[CostObjectEditCode02] [char](1) NOT NULL,
	[CostObjectEditCode03] [char](1) NOT NULL,
	[CostObjectEditCode04] [char](1) NOT NULL,
	[ItemEditCode] [char](1) NOT NULL,
	[FixedAssetPostingEditCode] [char](1) NOT NULL,
	[TypeCode] [char](1) NOT NULL,
	[GLAccountTaxableFlag] [char](1) NOT NULL,
	[TargetObjectAccount] [char](6) NOT NULL,
	[TargetSubsidiary] [char](8) NOT NULL,
	[PurgeFlag] [char](1) NOT NULL,
	[TaxRateArea] [char](10) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
	[Category01Desc2] [char](30) NOT NULL,
	[Category02Desc2] [char](30) NOT NULL,
	[Category03Desc2] [char](30) NOT NULL,
	[Category04Desc2] [char](30) NOT NULL,
	[Category05Desc2] [char](30) NOT NULL,
	[Category06Desc2] [char](30) NOT NULL,
	[Category07Desc2] [char](30) NOT NULL,
	[Category08Desc2] [char](30) NOT NULL,
	[Category09Desc2] [char](30) NOT NULL,
	[Category10Desc2] [char](30) NOT NULL,
	[Category11Desc2] [char](30) NOT NULL,
	[Category12Desc2] [char](30) NOT NULL,
	[Category13Desc2] [char](30) NOT NULL,
	[Category14Desc2] [char](30) NOT NULL,
	[Category15Desc2] [char](30) NOT NULL,
	[Category16Desc2] [char](30) NOT NULL,
	[Category17Desc2] [char](30) NOT NULL,
	[Category18Desc2] [char](30) NOT NULL,
	[Category19Desc2] [char](30) NOT NULL,
	[Category20Desc2] [char](30) NOT NULL,
	[Category21Desc2] [char](30) NOT NULL,
	[Category22Desc2] [char](30) NOT NULL,
	[Category23Desc2] [char](30) NOT NULL,
	[Category24Desc2] [char](30) NOT NULL,
	[Category25Desc2] [char](30) NOT NULL,
	[Category26Desc2] [char](30) NOT NULL,
	[Category27Desc2] [char](30) NOT NULL,
	[Category28Desc2] [char](30) NOT NULL,
	[Category29Desc2] [char](30) NOT NULL,
	[Category30Desc2] [char](30) NOT NULL,
	[Category31Desc2] [char](30) NOT NULL,
	[Category32Desc2] [char](30) NOT NULL,
	[Category33Desc2] [char](30) NOT NULL,
	[Category34Desc2] [char](30) NOT NULL,
	[Category35Desc2] [char](30) NOT NULL,
	[Category36Desc2] [char](30) NOT NULL,
	[Category37Desc2] [char](30) NOT NULL,
	[Category38Desc2] [char](30) NOT NULL,
	[Category39Desc2] [char](30) NOT NULL,
	[Category40Desc2] [char](30) NOT NULL,
	[Category41Desc2] [char](30) NOT NULL,
	[Category42Desc2] [char](30) NOT NULL,
	[Category43Desc2] [char](30) NOT NULL,
 CONSTRAINT [PK_JDEGAAccountMaster] PRIMARY KEY CLUSTERED 
(
	[AccountID] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEGAAccountMaster] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEGAAccountLedger]    Script Date: 5/8/13 12:13:27 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEGAAccountLedger]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEGAAccountLedger](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[DocumentCompany] [char](5) NOT NULL,
	[DocumentType] [char](2) NOT NULL,
	[DocumentNumber] [int] NOT NULL,
	[GLDate] [datetime] NOT NULL,
	[JournalEntryLineNumber] [decimal](20, 7) NOT NULL,
	[LineExtensionCode] [char](2) NOT NULL,
	[GLPostedCode] [char](1) NOT NULL,
	[BatchNumber] [int] NOT NULL,
	[BatchType] [char](2) NOT NULL,
	[BatchDate] [datetime] NOT NULL,
	[BatchSystemDate] [datetime] NOT NULL,
	[BatchTime] [int] NOT NULL,
	[CompanyNumber] [char](5) NOT NULL,
	[AccountNumber] [char](29) NOT NULL,
	[AccountMode01] [char](1) NOT NULL,
	[AccountID] [char](8) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[Object] [char](6) NOT NULL,
	[Subsidiary] [char](8) NOT NULL,
	[SubLedger] [char](8) NOT NULL,
	[SubledgerType] [char](1) NOT NULL,
	[LedgerTypeCode] [char](2) NOT NULL,
	[GLPeriodNumber] [int] NOT NULL,
	[Century] [int] NOT NULL,
	[FiscalYear] [int] NOT NULL,
	[FiscalQuarter] [char](4) NOT NULL,
	[CurrencyCode] [char](3) NOT NULL,
	[CurrencyConversionRateSpot] [decimal](20, 7) NOT NULL,
	[HistoricalExchangeRate] [decimal](20, 7) NOT NULL,
	[HistoricalDate] [datetime] NOT NULL,
	[Amount] [decimal](20, 7) NOT NULL,
	[Units] [decimal](20, 7) NOT NULL,
	[UnitOfMeasure] [char](2) NOT NULL,
	[GLOffset] [char](4) NOT NULL,
	[ReverseOrVoidEntry] [char](1) NOT NULL,
	[ExplanationDescription] [char](30) NOT NULL,
	[RemarkExplanation] [char](30) NOT NULL,
	[Ref1JEVouchInvEtc] [char](8) NOT NULL,
	[Ref2AddressNumber] [char](8) NOT NULL,
	[Ref3AccountReconciliation] [char](8) NOT NULL,
	[PayItem] [char](3) NOT NULL,
	[OriginalDocumentNumber] [int] NOT NULL,
	[OriginalDocumentType] [char](2) NOT NULL,
	[OriginalPayItem] [char](3) NOT NULL,
	[PurchaseOrderDocumentCompany] [char](5) NOT NULL,
	[OriginalOrderDocumentCompany] [char](5) NOT NULL,
	[PurchaseOrderDocumentType] [char](2) NOT NULL,
	[AddressNumber] [int] NOT NULL,
	[PaymentNumber] [char](8) NOT NULL,
	[CheckDate] [datetime] NOT NULL,
	[CheckClearedDate] [datetime] NOT NULL,
	[SerialNumber] [char](25) NOT NULL,
	[BatchRearEndPostedCode] [char](1) NOT NULL,
	[Reconciled] [char](1) NOT NULL,
	[SummarizedCode] [char](1) NOT NULL,
	[PurgeCode] [char](1) NOT NULL,
	[FlagFor1099] [char](1) NOT NULL,
	[AlternateGLPostingCode1] [char](1) NOT NULL,
	[AlternateGLPostingCode2] [char](1) NOT NULL,
	[AlternateGLPostingCode3] [char](1) NOT NULL,
	[AlternateGLPostingCode4] [char](1) NOT NULL,
	[MultiCurrencyJournalEntry] [char](1) NOT NULL,
	[CashBasisAccountingPostCode] [char](1) NOT NULL,
	[CommitmentReliefFlag] [char](1) NOT NULL,
	[BillingControl] [char](1) NOT NULL,
	[CurrencyUpdate] [char](1) NOT NULL,
	[LaborCostingFlag] [char](1) NOT NULL,
	[FutureUseFlag11] [char](1) NOT NULL,
	[FutureUseFlag12] [char](1) NOT NULL,
	[FutureUseFlag13] [char](1) NOT NULL,
	[FutureUseFlag14] [char](1) NOT NULL,
	[ConsumptionTaxCrossReference] [char](1) NOT NULL,
	[FutureUseFlag16] [char](1) NOT NULL,
	[DeleteNotAllowed] [char](1) NOT NULL,
	[FutureUseFlag18] [char](1) NOT NULL,
	[FutureUseFlag19] [char](1) NOT NULL,
	[LeaseCostLedgerPostedCode] [char](1) NOT NULL,
	[BillCode] [char](1) NOT NULL,
	[InvoiceNumber] [char](25) NOT NULL,
	[InvoiceDate] [datetime] NOT NULL,
	[Phase] [char](4) NOT NULL,
	[PONumber] [char](8) NOT NULL,
	[PurchaseOrderSuffix] [char](3) NOT NULL,
	[OrderTypeCode] [char](2) NOT NULL,
	[LineNumber] [decimal](20, 7) NOT NULL,
	[FiscalYearWeekly] [int] NOT NULL,
	[FiscalPeriodWeekly] [int] NOT NULL,
	[ClosedStatement] [char](1) NOT NULL,
	[OperationsSequenceNumber] [decimal](20, 7) NOT NULL,
	[JobType] [char](6) NOT NULL,
	[JobStep] [char](4) NOT NULL,
	[HomeBusinessUnit] [char](12) NOT NULL,
	[DOISub] [int] NOT NULL,
	[OutsiderLeaseWellID] [char](25) NOT NULL,
	[IDType] [char](2) NOT NULL,
	[ServiceDateTax] [datetime] NOT NULL,
	[TransactionOriginator] [char](10) NOT NULL,
	[RegistrationNumber] [int] NOT NULL,
	[InternalPaymentID] [decimal](15, 0) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[LastTimeUpdated] [int] NOT NULL,
	[ManagerialAnalysisCode1] [char](12) NOT NULL,
	[ManagerialAnalysisCode2] [char](12) NOT NULL,
	[ManagerialAnalysisCode3] [char](12) NOT NULL,
	[ManagerialAnalysisCode4] [char](12) NOT NULL,
	[ManagerialAnalysisType1] [char](1) NOT NULL,
	[ManagerialAnalysisType2] [char](1) NOT NULL,
	[ManagerialAnalysisType3] [char](1) NOT NULL,
	[ManagerialAnalysisType4] [char](1) NOT NULL,
	[ItemNumberShort] [int] NOT NULL,
	[PostingCode1ManagerialAccount] [char](1) NOT NULL,
	[PostingCode2ManagerialAccount] [char](1) NOT NULL,
	[PostingCode3ManagerialAccount] [char](1) NOT NULL,
	[PostingCode4ManagerialAccount] [char](1) NOT NULL,
	[PostingCode5ManagerialAccount] [char](1) NOT NULL,
	[PostingCode6ManagerialAccount] [char](1) NOT NULL,
	[PostingCode7ManagerialAccount] [char](1) NOT NULL,
	[PostingCode8ManagerialAccount] [char](1) NOT NULL,
	[PostingCode9ManagerialAccount] [char](1) NOT NULL,
	[PostingCode10ManagerialAccount] [char](1) NOT NULL,
	[CurrencyCodeBase] [char](3) NOT NULL,
	[CurrencyModeForeignDomEntry] [char](1) NOT NULL,
	[PurgeFlag] [char](1) NOT NULL,
	[TaxRateArea] [char](10) NOT NULL,
	[TaxExplCode1] [char](2) NOT NULL,
	[TaxShortItemNumber] [int] NOT NULL,
	[ActivityBasedCostingActyCode] [char](10) NOT NULL,
	[FutureUseFlag] [char](1) NOT NULL,
	[CurrencyAmount] [decimal](20, 7) NOT NULL,
	[DistributionLineNumber] [decimal](20, 7) NOT NULL,
	[ReceiptNumber] [char](25) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEGAAccountLedger] PRIMARY KEY CLUSTERED 
(
	[DocumentNumber] ASC,
	[DocumentType] ASC,
	[DocumentCompany] ASC,
	[GLDate] ASC,
	[JournalEntryLineNumber] ASC,
	[LedgerTypeCode] ASC,
	[LineExtensionCode] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEGAAccountLedger] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEGAAccountBalances]    Script Date: 5/8/13 12:13:27 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEGAAccountBalances]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEGAAccountBalances](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[AccountID] [char](8) NOT NULL,
	[Century] [int] NOT NULL,
	[FiscalYear] [int] NOT NULL,
	[FiscalQuarter] [char](4) NOT NULL,
	[LedgerTypeCode] [char](2) NOT NULL,
	[SubLedger] [char](8) NOT NULL,
	[CompanyNumber] [char](5) NOT NULL,
	[PriorYearCloseBalance] [decimal](20, 7) NOT NULL,
	[NetPosting01] [decimal](20, 7) NOT NULL,
	[NetPosting02] [decimal](20, 7) NOT NULL,
	[NetPosting03] [decimal](20, 7) NOT NULL,
	[NetPosting04] [decimal](20, 7) NOT NULL,
	[NetPosting05] [decimal](20, 7) NOT NULL,
	[NetPosting06] [decimal](20, 7) NOT NULL,
	[NetPosting07] [decimal](20, 7) NOT NULL,
	[NetPosting08] [decimal](20, 7) NOT NULL,
	[NetPosting09] [decimal](20, 7) NOT NULL,
	[NetPosting10] [decimal](20, 7) NOT NULL,
	[NetPosting11] [decimal](20, 7) NOT NULL,
	[NetPosting12] [decimal](20, 7) NOT NULL,
	[NetPosting13] [decimal](20, 7) NOT NULL,
	[NetPosting14] [decimal](20, 7) NOT NULL,
	[PriorYearEndNetPosting] [decimal](20, 7) NOT NULL,
	[WeekToDateNetPosting] [decimal](20, 7) NOT NULL,
	[OriginalBeginningBudget] [decimal](20, 7) NOT NULL,
	[MemoBudgetChange] [decimal](20, 7) NOT NULL,
	[PercentComplete] [decimal](20, 7) NOT NULL,
	[MemoCommitmentChanges] [decimal](20, 7) NOT NULL,
	[RequestedBudget] [decimal](20, 7) NOT NULL,
	[ApprovedBudget] [decimal](20, 7) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[Object] [char](6) NOT NULL,
	[Subsidiary] [char](8) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[SubledgerType] [char](1) NOT NULL,
	[LastTimeUpdated] [int] NOT NULL,
	[CurrencyCodeFrom] [char](3) NOT NULL,
	[CurrencyCodeIn] [char](3) NOT NULL,
	[BalanceForward] [decimal](20, 7) NOT NULL,
	[PurgeFlag] [char](1) NOT NULL,
	[NetDebitPosting01] [decimal](20, 7) NOT NULL,
	[NetDebitPosting02] [decimal](20, 7) NOT NULL,
	[NetDebitPosting03] [decimal](20, 7) NOT NULL,
	[NetDebitPosting04] [decimal](20, 7) NOT NULL,
	[NetDebitPosting05] [decimal](20, 7) NOT NULL,
	[NetDebitPosting06] [decimal](20, 7) NOT NULL,
	[NetDebitPosting07] [decimal](20, 7) NOT NULL,
	[NetDebitPosting08] [decimal](20, 7) NOT NULL,
	[NetDebitPosting09] [decimal](20, 7) NOT NULL,
	[NetDebitPosting10] [decimal](20, 7) NOT NULL,
	[NetDebitPosting11] [decimal](20, 7) NOT NULL,
	[NetDebitPosting12] [decimal](20, 7) NOT NULL,
	[NetDebitPosting13] [decimal](20, 7) NOT NULL,
	[NetDebitPosting14] [decimal](20, 7) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEGAAccountBalances] PRIMARY KEY CLUSTERED 
(
	[AccountID] ASC,
	[Century] ASC,
	[FiscalYear] ASC,
	[FiscalQuarter] ASC,
	[LedgerTypeCode] ASC,
	[SubLedger] ASC,
	[SubledgerType] ASC,
	[CurrencyCodeFrom] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEGAAccountBalances] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEPOPurchaseOrderDetail]    Script Date: 5/8/13 12:13:28 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEPOPurchaseOrderDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEPOPurchaseOrderDetail](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[OrderNumberDocumentCompany] [char](5) NOT NULL,
	[OrderNumber] [int] NOT NULL,
	[OrderTypeCode] [char](2) NOT NULL,
	[OrderSuffix] [char](3) NOT NULL,
	[LineNumber] [decimal](20, 7) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[CompanyNumber] [char](5) NOT NULL,
	[OriginalOrderDocumentCompany] [char](5) NOT NULL,
	[OriginalOrderNumber] [char](8) NOT NULL,
	[OriginalOrderTypeCode] [char](2) NOT NULL,
	[OriginalLineNumber] [decimal](20, 7) NOT NULL,
	[RelatedOrderKeyCompany] [char](5) NOT NULL,
	[RelatedPoSoWoNumber] [char](8) NOT NULL,
	[RelatedPoSoWoType] [char](2) NOT NULL,
	[RelatedPOSOLineNumber] [decimal](20, 7) NOT NULL,
	[ContractNumber] [char](12) NOT NULL,
	[ContractSupplement] [int] NOT NULL,
	[ContractBalancesUpdated] [char](1) NOT NULL,
	[AddressNumber] [int] NOT NULL,
	[ShipTo] [int] NOT NULL,
	[RequestedDate] [datetime] NOT NULL,
	[TransactionDate] [datetime] NOT NULL,
	[PromisedDeliveryDate] [datetime] NOT NULL,
	[OriginalPromisedDate] [datetime] NOT NULL,
	[ActualDeliveryDate] [datetime] NOT NULL,
	[CancelDate] [datetime] NOT NULL,
	[PriceEffectiveDate] [datetime] NOT NULL,
	[ShipDate] [datetime] NOT NULL,
	[FutureUseDate] [datetime] NOT NULL,
	[ServiceDateTax] [datetime] NOT NULL,
	[GLDate] [datetime] NOT NULL,
	[GLPeriodNumber] [int] NOT NULL,
	[Reference1] [char](25) NOT NULL,
	[Reference2] [char](25) NOT NULL,
	[ItemNumber] [int] NOT NULL,
	[ItemNumber02] [char](25) NOT NULL,
	[ItemNumber03] [char](25) NOT NULL,
	[Location] [char](20) NOT NULL,
	[LotNumber] [char](30) NOT NULL,
	[FromGrade] [char](3) NOT NULL,
	[ThruGrade] [char](3) NOT NULL,
	[FromPotency] [decimal](20, 7) NOT NULL,
	[ThruPotency] [decimal](20, 7) NOT NULL,
	[Description01] [char](30) NOT NULL,
	[Description02] [char](30) NOT NULL,
	[LineType] [char](2) NOT NULL,
	[StatusCodeNext] [char](3) NOT NULL,
	[StatusCodeLast] [char](3) NOT NULL,
	[RelatedItemNumber] [char](8) NOT NULL,
	[SalesCategory01Code] [char](3) NOT NULL,
	[SalesCategory02Code] [char](3) NOT NULL,
	[SalesCategory03Code] [char](3) NOT NULL,
	[SalesCategory04Code] [char](3) NOT NULL,
	[SalesCategory05Code] [char](3) NOT NULL,
	[PurchasingCategory01Code] [char](3) NOT NULL,
	[PurchasingCategory02Code] [char](3) NOT NULL,
	[PurchasingCategory03Code] [char](3) NOT NULL,
	[PurchasingCategory04Code] [char](3) NOT NULL,
	[PurchasingCategory05Code] [char](3) NOT NULL,
	[UnitOfMeasureAsInput] [char](2) NOT NULL,
	[QuantityOrdered] [decimal](22, 7) NOT NULL,
	[ChangeOrderQuantity] [decimal](22, 7) NOT NULL,
	[QuantityOpen] [decimal](22, 7) NOT NULL,
	[ReceivedQuantity] [decimal](22, 7) NOT NULL,
	[QuantityCumulativeReceived] [decimal](22, 7) NOT NULL,
	[QuantityRelieved] [decimal](22, 7) NOT NULL,
	[OtherQuantity] [char](1) NOT NULL,
	[PurchasingUnitPrice] [decimal](20, 7) NOT NULL,
	[ExtendedPrice] [decimal](20, 7) NOT NULL,
	[ChangeAmount] [decimal](20, 7) NOT NULL,
	[AmountOpen] [decimal](20, 7) NOT NULL,
	[AmountReceived] [decimal](20, 7) NOT NULL,
	[AmountRelieved] [decimal](20, 7) NOT NULL,
	[AmountFuture] [decimal](20, 7) NOT NULL,
	[TaxRelieved] [decimal](20, 7) NOT NULL,
	[PriceOverrideCode] [char](1) NOT NULL,
	[PurchasingUnitCost] [decimal](20, 7) NOT NULL,
	[ExtendedCost] [decimal](20, 7) NOT NULL,
	[CostOverrideCode] [char](1) NOT NULL,
	[PurchasingCostingMethod] [char](1) NOT NULL,
	[PrintMessage] [char](10) NOT NULL,
	[AdjustmentSchedule] [char](8) NOT NULL,
	[ItemPriceGroupCode] [char](8) NOT NULL,
	[PricingCategoryLevel] [char](3) NOT NULL,
	[Catalog] [char](8) NOT NULL,
	[DiscountFactor] [decimal](20, 7) NOT NULL,
	[PaymentTerms] [char](3) NOT NULL,
	[Taxable] [char](1) NOT NULL,
	[TaxExplanationCode] [char](2) NOT NULL,
	[TaxRateArea] [char](10) NOT NULL,
	[AssociatedText] [char](1) NOT NULL,
	[ContainerID] [char](20) NOT NULL,
	[CommodityCode] [char](15) NOT NULL,
	[NatureofTransaction] [char](2) NOT NULL,
	[FreightHandlingCode] [char](3) NOT NULL,
	[FreightCalculated] [char](1) NOT NULL,
	[ZoneNumber] [char](3) NOT NULL,
	[RateCodeFreightMisc] [char](10) NOT NULL,
	[RateTypeFreightMisc] [char](1) NOT NULL,
	[BuyerNumber] [int] NOT NULL,
	[CarrierCode] [int] NOT NULL,
	[ModeOfTransportation] [char](3) NOT NULL,
	[ConditionsOfTransportation] [char](3) NOT NULL,
	[ShippingCommodityClass] [char](3) NOT NULL,
	[ShippingConditionsCode] [char](3) NOT NULL,
	[UnitOfMeasurePrimary] [char](2) NOT NULL,
	[PrimaryQuantityOrdered] [decimal](22, 7) NOT NULL,
	[UnitOfMeasureSecondary] [char](2) NOT NULL,
	[SecondaryQuantityOrdered] [decimal](22, 7) NOT NULL,
	[UnitOfMeasurePurchas] [char](2) NOT NULL,
	[UnitWeight] [decimal](20, 7) NOT NULL,
	[WeightUOM] [char](2) NOT NULL,
	[UnitVolume] [decimal](20, 7) NOT NULL,
	[VolumeUOM] [char](2) NOT NULL,
	[GLOffset] [char](4) NOT NULL,
	[Century] [int] NOT NULL,
	[FiscalYear] [int] NOT NULL,
	[LineStatus] [char](2) NOT NULL,
	[ReasonCode] [char](3) NOT NULL,
	[ApplyFreight] [char](1) NOT NULL,
	[PostQuantities] [char](1) NOT NULL,
	[GrossWeight] [decimal](20, 7) NOT NULL,
	[GrossWeightUOM] [char](2) NOT NULL,
	[LedgerTypeCode] [char](2) NOT NULL,
	[AccountNumber] [char](29) NOT NULL,
	[AccountID] [char](8) NOT NULL,
	[PurchasingBusinessUnit] [char](12) NOT NULL,
	[ObjectAccount] [char](6) NOT NULL,
	[Subsidiary] [char](8) NOT NULL,
	[SubledgerType] [char](1) NOT NULL,
	[SubLedger] [char](8) NOT NULL,
	[SerialNumber] [char](25) NOT NULL,
	[CostComponentNumber] [int] NOT NULL,
	[ReferenceTag] [char](8) NOT NULL,
	[Phase] [char](4) NOT NULL,
	[PenCode] [char](4) NOT NULL,
	[Elevation] [char](3) NOT NULL,
	[Category01Code] [char](3) NOT NULL,
	[RetainageRule] [char](3) NOT NULL,
	[LocalTaxCode] [char](2) NOT NULL,
	[PurgeCode] [char](1) NOT NULL,
	[ProcessingMode] [char](1) NOT NULL,
	[ClosedStatement] [char](1) NOT NULL,
	[EvaluatedReceipt] [char](1) NOT NULL,
	[PrePayment] [char](1) NOT NULL,
	[FreezeCode] [char](1) NOT NULL,
	[MatchType] [char](1) NOT NULL,
	[RoutingProcess] [char](1) NOT NULL,
	[LeadtimeRecalculated] [char](1) NOT NULL,
	[TransferOrDirectShipFlag] [char](1) NOT NULL,
	[PurchaseOrderStatus02] [char](1) NOT NULL,
	[PurchaseOrderStatus03] [char](1) NOT NULL,
	[PurchaseOrderStatus04] [char](1) NOT NULL,
	[PurchaseOrderStatus05] [char](1) NOT NULL,
	[PurchaseOrderStatus06] [char](1) NOT NULL,
	[PurchaseOrderStatus07] [char](1) NOT NULL,
	[PurchaseOrderStatus08] [char](1) NOT NULL,
	[PurchaseOrderStatus09] [char](1) NOT NULL,
	[PurchaseOrderStatus10] [char](1) NOT NULL,
	[SendMethod] [char](1) NOT NULL,
	[ApprovalRouteCode] [char](12) NOT NULL,
	[ChangeOrder] [int] NOT NULL,
	[ChangeOrderType] [char](2) NOT NULL,
	[ChangeOrderNumber] [int] NOT NULL,
	[ChangeOrderLineNumber] [decimal](20, 7) NOT NULL,
	[CurrencyCode] [char](3) NOT NULL,
	[CurrencyConversionRateSpot] [decimal](20, 7) NOT NULL,
	[ForeignUnitCost] [decimal](20, 7) NOT NULL,
	[ForeignExtendedPrice] [decimal](20, 7) NOT NULL,
	[ForeignUnitCost2] [decimal](20, 7) NOT NULL,
	[ForeignExtendedCost] [decimal](20, 7) NOT NULL,
	[ForeignChangedAmount] [decimal](20, 7) NOT NULL,
	[ForeignOpenAmount] [decimal](20, 7) NOT NULL,
	[ForeignAmountReceived] [decimal](20, 7) NOT NULL,
	[UserReservedCode] [char](2) NOT NULL,
	[UserReservedDate] [datetime] NOT NULL,
	[UserReservedAmount] [decimal](20, 7) NOT NULL,
	[UserReservedNumber] [int] NOT NULL,
	[UserReservedReference] [char](15) NOT NULL,
	[TransactionOriginator] [char](10) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[OutsideReference2] [char](25) NOT NULL,
	[OutsideReference1] [char](25) NOT NULL,
	[ShipmentNumber] [int] NOT NULL,
	[RequestedShipTime] [int] NOT NULL,
	[ProjectNumber] [int] NOT NULL,
	[DocumentPayItemOriginal] [char](3) NOT NULL,
	[ItemRevisionLevel] [char](3) NOT NULL,
	[MatrixControlLineNumber] [decimal](20, 7) NOT NULL,
	[MultipleAccounts] [char](1) NOT NULL,
	[KitMasterLineNumber] [decimal](20, 7) NOT NULL,
	[AmountForeignTaxRelieved] [decimal](20, 7) NOT NULL,
	[DualUnitOfMeasureItem] [char](1) NOT NULL,
	[RequestedDeliveryTime] [int] NOT NULL,
	[LotEffectivityDate] [datetime] NOT NULL,
	[AmountForeignTax] [decimal](20, 7) NOT NULL,
	[ComponentLineNumber] [decimal](20, 7) NOT NULL,
	[ChangeOrderTimeofDay] [int] NOT NULL,
	[TimeScheduledRequiredHHMMSS] [int] NOT NULL,
	[ShiftCodeScheduledRequired] [char](1) NOT NULL,
	[ChangeOrderDateUpdated] [datetime] NOT NULL,
	[CurrencyCodeBase] [char](3) NOT NULL,
	[Reference] [char](25) NOT NULL,
	[LoadNumber] [int] NOT NULL,
	[AddressNumberMarkfor] [int] NOT NULL,
	[PromotionID] [char](12) NOT NULL,
	[UniqueKeyIDInternal] [decimal](15, 0) NOT NULL,
	[UNSPSCCommodityCode] [char](8) NOT NULL,
	[CommodityCode01] [char](15) NOT NULL,
	[RelatedOrderSuffix] [char](3) NOT NULL,
	[HarvestID] [int] NOT NULL,
	[ContractID] [int] NOT NULL,
	[ContractDetailID] [int] NOT NULL,
	[ManualOverrideAdjustmentFlag] [char](1) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEPOPurchaseOrderDetail] PRIMARY KEY CLUSTERED 
(
	[OrderNumber] ASC,
	[OrderNumberDocumentCompany] ASC,
	[LineNumber] ASC,
	[OrderTypeCode] ASC,
	[OrderSuffix] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEPOPurchaseOrderDetail] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDEWOWorkOrderMasterFile]    Script Date: 5/8/13 12:13:28 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDEWOWorkOrderMasterFile]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDEWOWorkOrderMasterFile](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[OrderTypeCode] [char](2) NOT NULL,
	[OrderNumber] [int] NOT NULL,
	[OrderSuffix] [char](3) NOT NULL,
	[RelatedPoSoWoType] [char](2) NOT NULL,
	[RelatedPoSoWoNumber] [char](8) NOT NULL,
	[LineNumber] [decimal](20, 7) NOT NULL,
	[PegtoWorkOrder] [int] NOT NULL,
	[NumberParentWONumber] [char](8) NOT NULL,
	[TypeWO] [char](1) NOT NULL,
	[PriorityWO] [char](1) NOT NULL,
	[Description01] [char](30) NOT NULL,
	[StatusComment] [char](30) NOT NULL,
	[CompanyNumber] [char](5) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[Branch] [char](12) NOT NULL,
	[Location] [char](20) NOT NULL,
	[Aisle] [char](8) NOT NULL,
	[Bin] [char](8) NOT NULL,
	[StatusCodeWO] [char](2) NOT NULL,
	[DateStatusChanged] [datetime] NOT NULL,
	[Subsidiary] [char](8) NOT NULL,
	[AddressNumber] [int] NOT NULL,
	[AddressNumberOriginator] [int] NOT NULL,
	[AddressNumberManager] [int] NOT NULL,
	[Supervisor] [int] NOT NULL,
	[AddressNumberAssignedTo] [int] NOT NULL,
	[DateWOPlannedCompleted] [datetime] NOT NULL,
	[AddressNumberInspector] [int] NOT NULL,
	[NextAddressNumber] [int] NOT NULL,
	[TransactionDate] [datetime] NOT NULL,
	[DateStartJulian] [datetime] NOT NULL,
	[RequestedDate] [datetime] NOT NULL,
	[DateCompletionJulian] [datetime] NOT NULL,
	[DateAssignedto] [datetime] NOT NULL,
	[DateAssignedtoInspector] [datetime] NOT NULL,
	[DatePaperPrintedDate] [datetime] NOT NULL,
	[Phase] [char](4) NOT NULL,
	[CategoriesWorkOrder02] [char](3) NOT NULL,
	[CategoriesWorkOrder03] [char](3) NOT NULL,
	[CategoriesWorkOrder04] [char](3) NOT NULL,
	[CategoriesWorkOrder05] [char](3) NOT NULL,
	[JDEConsultingStatus] [char](3) NOT NULL,
	[JDEConsultingServiceType] [char](3) NOT NULL,
	[JDEConsultingSkillType] [char](3) NOT NULL,
	[JDEConsultingExperienceLevel] [char](3) NOT NULL,
	[CategoriesWorkOrder10] [char](3) NOT NULL,
	[Reference1] [char](25) NOT NULL,
	[Reference2] [char](25) NOT NULL,
	[AmountEstimated] [decimal](20, 7) NOT NULL,
	[CrewSize] [int] NOT NULL,
	[RateRevenueOverrideRateMarkup] [decimal](20, 7) NOT NULL,
	[PayDeductionBenefitType] [char](5) NOT NULL,
	[AmountChangetoOriginalDollars] [decimal](20, 7) NOT NULL,
	[HoursEstimated] [decimal](20, 7) NOT NULL,
	[HoursChangetoOriginalHours] [decimal](20, 7) NOT NULL,
	[AmountActual] [decimal](20, 7) NOT NULL,
	[HoursActual] [decimal](20, 7) NOT NULL,
	[ItemNumber] [int] NOT NULL,
	[ItemNumber03] [char](25) NOT NULL,
	[ItemNumber02] [char](25) NOT NULL,
	[AssetItemNumber] [int] NOT NULL,
	[UnitorTagNumber] [char](12) NOT NULL,
	[QuantityOrdered] [decimal](22, 7) NOT NULL,
	[QuantityBackordered] [decimal](22, 7) NOT NULL,
	[QuantityCanceled] [decimal](22, 7) NOT NULL,
	[QuantityShipped] [decimal](22, 7) NOT NULL,
	[QuantityShippedToDate] [decimal](22, 7) NOT NULL,
	[UnitOfMeasureAsInput] [char](2) NOT NULL,
	[MessageNumber] [char](10) NOT NULL,
	[TimeBeginningHHMMSS] [int] NOT NULL,
	[TypeBillofMaterial] [char](3) NOT NULL,
	[TypeofRouting] [char](3) NOT NULL,
	[WOPickListPrinted] [char](1) NOT NULL,
	[PostingEditCode] [char](1) NOT NULL,
	[VarianceFlag] [char](1) NOT NULL,
	[BillofMaterialN] [char](1) NOT NULL,
	[RouteSheetN] [char](1) NOT NULL,
	[WorkOrderFlashMessage] [char](1) NOT NULL,
	[FreezeCode] [char](1) NOT NULL,
	[IndentedCode] [char](1) NOT NULL,
	[ResequenceCode] [int] NOT NULL,
	[AmountMilesorHoursunits] [decimal](20, 7) NOT NULL,
	[DateScheduledTickler] [datetime] NOT NULL,
	[MemoBudgetChange] [decimal](20, 7) NOT NULL,
	[PercentComplete] [decimal](20, 7) NOT NULL,
	[LeadtimeLevel] [int] NOT NULL,
	[LeadtimeCumulative] [int] NOT NULL,
	[HoursUnaccountedDirectLabor] [decimal](20, 7) NOT NULL,
	[LotNumber] [char](30) NOT NULL,
	[LotPotency] [decimal](20, 7) NOT NULL,
	[LotGrade] [char](3) NOT NULL,
	[RatioCriticalRatioPriority1] [decimal](20, 7) NOT NULL,
	[RatioCriticalRatioPriority2] [decimal](20, 7) NOT NULL,
	[DocumentType] [char](2) NOT NULL,
	[SubledgerInactiveCode] [char](1) NOT NULL,
	[RelatedOrderKeyCompany] [char](5) NOT NULL,
	[BillRevisionLevel] [char](3) NOT NULL,
	[RoutingRevisionLevel] [char](3) NOT NULL,
	[DrawingChange] [char](1) NOT NULL,
	[RoutingChange] [char](1) NOT NULL,
	[NewPartNumber] [char](1) NOT NULL,
	[ReasonforECO] [char](2) NOT NULL,
	[PhaseIn] [char](3) NOT NULL,
	[ExistingDisposition] [char](3) NOT NULL,
	[BOMChange] [char](1) NOT NULL,
	[UserReservedCode] [char](2) NOT NULL,
	[UserReservedDate] [datetime] NOT NULL,
	[UserReservedAmount] [decimal](20, 7) NOT NULL,
	[UserReservedNumber] [int] NOT NULL,
	[UserReservedReference] [char](15) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[ParentNumber] [int] NOT NULL,
	[NextStatusWO] [char](2) NOT NULL,
	[CriticalityWorkOrder] [int] NOT NULL,
	[EstimatedDowntimeHours] [int] NOT NULL,
	[ActualDowntimeHours] [int] NOT NULL,
	[ServiceAddressNumber] [int] NOT NULL,
	[MeterPosition] [int] NOT NULL,
	[ApprovalType] [char](3) NOT NULL,
	[AmountEstimatedLabor] [decimal](20, 7) NOT NULL,
	[AmountEstimatedMaterial] [decimal](20, 7) NOT NULL,
	[AmountEstimatedOther] [decimal](20, 7) NOT NULL,
	[AmountActualLabor] [decimal](20, 7) NOT NULL,
	[AmountActualMaterial] [decimal](20, 7) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDEWOWorkOrderMasterFile] PRIMARY KEY CLUSTERED 
(
	[OrderNumber] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDEWOWorkOrderMasterFile] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDESOSalesOrderDetailHistory]    Script Date: 5/8/13 12:13:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDESOSalesOrderDetailHistory]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDESOSalesOrderDetailHistory](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[OrderNumberDocumentCompany] [char](5) NOT NULL,
	[OrderNumber] [int] NOT NULL,
	[OrderTypeCode] [char](2) NOT NULL,
	[LineNumber] [decimal](20, 7) NOT NULL,
	[OrderSuffix] [char](3) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[CompanyNumber] [char](5) NOT NULL,
	[OriginalOrderDocumentCompany] [char](5) NOT NULL,
	[OriginalOrderNumber] [char](8) NOT NULL,
	[OriginalOrderTypeCode] [char](2) NOT NULL,
	[OriginalLineNumber] [decimal](20, 7) NOT NULL,
	[RelatedOrderKeyCompany] [char](5) NOT NULL,
	[RelatedPoSoWoNumber] [char](8) NOT NULL,
	[RelatedPoSoWoType] [char](2) NOT NULL,
	[RelatedPOSOLineNumber] [decimal](20, 7) NOT NULL,
	[ContractNumber] [char](12) NOT NULL,
	[ContractSupplement] [int] NOT NULL,
	[ContractBalancesUpdated] [char](1) NOT NULL,
	[AddressNumber] [int] NOT NULL,
	[ShipToNumber] [int] NOT NULL,
	[ParentNumber] [int] NOT NULL,
	[RequestedDate] [datetime] NOT NULL,
	[TransactionDate] [datetime] NOT NULL,
	[PromisedDeliveryDate] [datetime] NOT NULL,
	[OriginalPromisedDate] [datetime] NOT NULL,
	[ActualDeliveryDate] [datetime] NOT NULL,
	[InvoiceDate] [datetime] NOT NULL,
	[CancelDate] [datetime] NOT NULL,
	[GLDate] [datetime] NOT NULL,
	[PromisedDelivery] [datetime] NOT NULL,
	[PriceEffectiveDate] [datetime] NOT NULL,
	[ShipDate] [datetime] NOT NULL,
	[FutureUseDate] [datetime] NOT NULL,
	[Reference1] [char](25) NOT NULL,
	[Reference2] [char](25) NOT NULL,
	[ItemNumber] [int] NOT NULL,
	[ItemNumber02] [char](25) NOT NULL,
	[ItemNumber03] [char](25) NOT NULL,
	[Location] [char](20) NOT NULL,
	[LotNumber] [char](30) NOT NULL,
	[FromGrade] [char](3) NOT NULL,
	[ThruGrade] [char](3) NOT NULL,
	[FromPotency] [decimal](20, 7) NOT NULL,
	[ThruPotency] [decimal](20, 7) NOT NULL,
	[DaysBeforeExpiration] [int] NOT NULL,
	[Description01] [char](30) NOT NULL,
	[Description02] [char](30) NOT NULL,
	[LineType] [char](2) NOT NULL,
	[StatusCodeNext] [char](3) NOT NULL,
	[StatusCodeLast] [char](3) NOT NULL,
	[HeaderBusinessUnit] [char](12) NOT NULL,
	[RelatedItemNumber] [char](8) NOT NULL,
	[KitMasterLineNumber] [decimal](20, 7) NOT NULL,
	[ComponentLineNumber] [decimal](20, 7) NOT NULL,
	[RelatedKitComponent] [int] NOT NULL,
	[NumberOfComponentPerParent] [decimal](22, 7) NOT NULL,
	[SalesCategory01Code] [char](3) NOT NULL,
	[SalesCategory02Code] [char](3) NOT NULL,
	[SalesCategory03Code] [char](3) NOT NULL,
	[SalesCategory04Code] [char](3) NOT NULL,
	[SalesCategory05Code] [char](3) NOT NULL,
	[PurchasingCategory01Code] [char](3) NOT NULL,
	[PurchasingCategory02Code] [char](3) NOT NULL,
	[PurchasingCategory03Code] [char](3) NOT NULL,
	[PurchasingCategory04Code] [char](3) NOT NULL,
	[PurchasingCategory05Code] [char](3) NOT NULL,
	[UnitOfMeasureAsInput] [char](2) NOT NULL,
	[QuantityOrdered] [decimal](22, 7) NOT NULL,
	[QuantityShipped] [decimal](22, 7) NOT NULL,
	[QuantityBackordered] [decimal](22, 7) NOT NULL,
	[QuantityCanceled] [decimal](22, 7) NOT NULL,
	[FutureQuantityCommitted] [decimal](22, 7) NOT NULL,
	[QuantityOpen] [decimal](22, 7) NOT NULL,
	[QuantityShippedToDate] [decimal](22, 7) NOT NULL,
	[QuantityRelieved] [decimal](22, 7) NOT NULL,
	[CommittedHS] [char](1) NOT NULL,
	[OtherQuantity] [char](1) NOT NULL,
	[UnitPrice] [decimal](20, 7) NOT NULL,
	[ExtendedPrice] [decimal](20, 7) NOT NULL,
	[AmountOpen] [decimal](20, 7) NOT NULL,
	[PriceOverrideCode] [char](1) NOT NULL,
	[TemporaryPrice] [char](1) NOT NULL,
	[EnteredUOMForUnitPrice] [char](2) NOT NULL,
	[UnitListPrice] [decimal](20, 7) NOT NULL,
	[UnitCost] [decimal](20, 7) NOT NULL,
	[ExtendedCost] [decimal](20, 7) NOT NULL,
	[CostOverrideCode] [char](1) NOT NULL,
	[TransferCost] [decimal](20, 7) NOT NULL,
	[PrintMessage] [char](10) NOT NULL,
	[PaymentTerms] [char](3) NOT NULL,
	[PaymentInstrument] [char](1) NOT NULL,
	[BasedonDate] [char](1) NOT NULL,
	[TradeDiscount] [decimal](20, 7) NOT NULL,
	[TradeDiscountOld] [decimal](20, 7) NOT NULL,
	[AdjustmentSchedule] [char](8) NOT NULL,
	[ItemPriceGroupCode] [char](8) NOT NULL,
	[PricingCategoryLevel] [char](3) NOT NULL,
	[DiscountFactor] [decimal](20, 7) NOT NULL,
	[DiscFactorTypeDollarOrPercent] [char](1) NOT NULL,
	[DiscountApplicationType] [char](1) NOT NULL,
	[CashDiscountPercent] [decimal](20, 7) NOT NULL,
	[DocumentCompany] [char](5) NOT NULL,
	[DocumentNumber] [int] NOT NULL,
	[DocumentType] [char](2) NOT NULL,
	[OriginalDocumentNumber] [int] NOT NULL,
	[OriginalDocumentTypeCode] [char](2) NOT NULL,
	[OriginalDocumentCompany] [char](5) NOT NULL,
	[PickSlipNumber] [int] NOT NULL,
	[DeliveryNumber] [int] NOT NULL,
	[PromotionNumber] [char](8) NOT NULL,
	[DraftNumber] [int] NOT NULL,
	[SalesTaxable] [char](1) NOT NULL,
	[TaxRateArea] [char](10) NOT NULL,
	[TaxExplanationCode] [char](2) NOT NULL,
	[AssociatedText] [char](1) NOT NULL,
	[PriorityProcessingCode] [char](1) NOT NULL,
	[PrintedCode] [char](1) NOT NULL,
	[BackOrdersAllowed] [char](1) NOT NULL,
	[SubstitutesAllowed] [char](1) NOT NULL,
	[PartialShipmentsAllowed] [char](1) NOT NULL,
	[LineOfBusiness] [char](3) NOT NULL,
	[EndUse] [char](3) NOT NULL,
	[DutyStatus] [char](2) NOT NULL,
	[CommodityCode] [char](15) NOT NULL,
	[NatureofTransaction] [char](2) NOT NULL,
	[PrimaryLastSupplierNumber] [int] NOT NULL,
	[BuyerNumber] [int] NOT NULL,
	[PreferredCarrierSales] [int] NOT NULL,
	[ModeOfTransportation] [char](3) NOT NULL,
	[ConditionsOfTransportation] [char](3) NOT NULL,
	[RouteCode] [char](3) NOT NULL,
	[StopCode] [char](3) NOT NULL,
	[ZoneNumber] [char](3) NOT NULL,
	[ContainerID] [char](20) NOT NULL,
	[FreightHandlingCode] [char](3) NOT NULL,
	[ApplyFreightYN] [char](1) NOT NULL,
	[ApplyFreight] [char](1) NOT NULL,
	[FreightCalculated] [char](1) NOT NULL,
	[RateCodeFreightMisc] [char](10) NOT NULL,
	[RateTypeFreightMisc] [char](1) NOT NULL,
	[ShippingCommodityClass] [char](3) NOT NULL,
	[ShippingConditionsCode] [char](3) NOT NULL,
	[LotSerialNumber] [char](30) NOT NULL,
	[UnitOfMeasurePrimary] [char](2) NOT NULL,
	[PrimaryQuantityOrdered] [decimal](22, 7) NOT NULL,
	[UnitOfMeasureSecondary] [char](2) NOT NULL,
	[SecondaryQuantityOrdered] [decimal](22, 7) NOT NULL,
	[UnitOfMeasurePricing] [char](2) NOT NULL,
	[UnitWeight] [decimal](20, 7) NOT NULL,
	[WeightUOM] [char](2) NOT NULL,
	[UnitVolume] [decimal](20, 7) NOT NULL,
	[VolumeUOM] [char](2) NOT NULL,
	[BasketRepriceGroup] [char](8) NOT NULL,
	[OrderRepriceGroup] [char](8) NOT NULL,
	[OrderRepricedIndicator] [char](1) NOT NULL,
	[InventoryCostingMethod] [char](2) NOT NULL,
	[CommitmentMethod] [char](1) NOT NULL,
	[GLOffset] [char](4) NOT NULL,
	[Century] [int] NOT NULL,
	[FiscalYear] [int] NOT NULL,
	[LineStatus] [char](2) NOT NULL,
	[SalesOrderStatus01] [char](1) NOT NULL,
	[SalesOrderStatus02] [char](1) NOT NULL,
	[SalesOrderStatus03] [char](1) NOT NULL,
	[SalesOrderStatus04] [char](1) NOT NULL,
	[SalesOrderStatus05] [char](1) NOT NULL,
	[SalesOrderStatus06] [char](1) NOT NULL,
	[SalesOrderStatus07] [char](1) NOT NULL,
	[SalesOrderStatus08] [char](1) NOT NULL,
	[SalesOrderStatus09] [char](1) NOT NULL,
	[SalesOrderStatus10] [char](1) NOT NULL,
	[SalesOrderStatus11] [char](1) NOT NULL,
	[SalesOrderStatus12] [char](1) NOT NULL,
	[SalesOrderStatus13] [char](1) NOT NULL,
	[SalesOrderStatus14] [char](1) NOT NULL,
	[SalesOrderStatus15] [char](1) NOT NULL,
	[SalespersonCode01] [int] NOT NULL,
	[SalespersonCommission01] [decimal](20, 7) NOT NULL,
	[SalespersonCode02] [int] NOT NULL,
	[SalespersonCommission02] [decimal](20, 7) NOT NULL,
	[ApplyCommission] [char](1) NOT NULL,
	[CommissionCategory] [char](8) NOT NULL,
	[ReasonCode] [char](3) NOT NULL,
	[GrossWeight] [decimal](20, 7) NOT NULL,
	[GrossWeightUOM] [char](2) NOT NULL,
	[AccountNumber] [char](29) NOT NULL,
	[AccountID] [char](8) NOT NULL,
	[PurchasingBusinessUnit] [char](12) NOT NULL,
	[ObjectAccount] [char](6) NOT NULL,
	[Subsidiary] [char](8) NOT NULL,
	[LedgerTypeCode] [char](2) NOT NULL,
	[SubLedger] [char](8) NOT NULL,
	[SubledgerType] [char](1) NOT NULL,
	[LocalTaxCode] [char](2) NOT NULL,
	[PriceCode1] [char](2) NOT NULL,
	[PriceCode2] [char](2) NOT NULL,
	[PriceCode3] [char](2) NOT NULL,
	[WarehouseStatusCode] [char](1) NOT NULL,
	[FreezeCode] [char](1) NOT NULL,
	[SendMethod] [char](1) NOT NULL,
	[CurrencyCode] [char](3) NOT NULL,
	[CurrencyConversionRateSpot] [decimal](20, 7) NOT NULL,
	[ForeignListPrice] [decimal](20, 7) NOT NULL,
	[ForeignUnitPrice] [decimal](20, 7) NOT NULL,
	[ForeignExtendedPrice] [decimal](20, 7) NOT NULL,
	[ForeignUnitCost2] [decimal](20, 7) NOT NULL,
	[ForeignExtendedCost] [decimal](20, 7) NOT NULL,
	[UserReservedCode] [char](2) NOT NULL,
	[UserReservedDate] [datetime] NOT NULL,
	[UserReservedAmount] [decimal](20, 7) NOT NULL,
	[UserReservedNumber] [int] NOT NULL,
	[UserReservedReference] [char](15) NOT NULL,
	[TransactionOriginator] [char](10) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[ManufacturingVarianceAcctFlag] [char](1) NOT NULL,
	[SalesOrderStatus17] [char](1) NOT NULL,
	[SalesOrderStatus18] [char](1) NOT NULL,
	[SalesOrderStatus19] [char](1) NOT NULL,
	[SalesOrderStatus20] [char](1) NOT NULL,
	[IntegrationReference01] [char](30) NOT NULL,
	[IntegrationReference02] [char](30) NOT NULL,
	[IntegrationReference03] [char](30) NOT NULL,
	[IntegrationReference04] [char](30) NOT NULL,
	[IntegrationReference05] [char](30) NOT NULL,
	[SourceofOrder] [int] NOT NULL,
	[Reference] [char](25) NOT NULL,
	[DemandUniqueKeyID] [int] NOT NULL,
	[PullSignal] [char](30) NOT NULL,
	[ReleaseNumber] [char](10) NOT NULL,
	[ScheduledShipmentTime] [int] NOT NULL,
	[TimeRelease] [int] NOT NULL,
	[DateRelease] [datetime] NOT NULL,
	[RequestedDeliveryTime] [int] NOT NULL,
	[ActualShipmentTime] [int] NOT NULL,
	[TimeOriginalPromisedDelivery] [int] NOT NULL,
	[TimeScheduledPick] [int] NOT NULL,
	[TimeFutureTime2] [int] NOT NULL,
	[CrossDockingFlag] [char](1) NOT NULL,
	[CrossDockingPriorityforSalesO] [decimal](28, 0) NOT NULL,
	[DualUnitOfMeasureItem] [char](1) NOT NULL,
	[BuyingSegmentCode] [char](10) NOT NULL,
	[CurrentBuyingSegmentCode] [char](10) NOT NULL,
	[ChangeOrderNumber] [int] NOT NULL,
	[AddressNumberDeliverTo] [int] NOT NULL,
	[PendingApprovalFlag] [char](1) NOT NULL,
	[RevisionReason] [char](6) NOT NULL,
	[MatrixControlLineNumber] [decimal](20, 7) NOT NULL,
	[ShipmentNumber] [int] NOT NULL,
	[PromisedDeliveryTime] [int] NOT NULL,
	[ProjectNumber] [int] NOT NULL,
	[SequenceNumber] [int] NOT NULL,
	[ItemRevisionLevel] [char](3) NOT NULL,
	[HoldOrdersCode] [char](2) NOT NULL,
	[BusinessUnitHeader] [char](12) NOT NULL,
	[BusinessUnitDemand] [char](12) NOT NULL,
	[CurrencyCodeBase] [char](3) NOT NULL,
	[DocumentLineNumberOriginal] [decimal](20, 7) NOT NULL,
	[CrossDockOrderCompanyOrderNum] [char](10) NOT NULL,
	[CrossDockOrderNo] [int] NOT NULL,
	[CrossDockOrderType] [char](4) NOT NULL,
	[CrossDockLineNumber] [decimal](20, 7) NOT NULL,
	[CrossDockOrderSuffix] [char](3) NOT NULL,
	[PortofEntryorExit] [char](6) NOT NULL,
	[PaymentTermsOverrideCode] [char](1) NOT NULL,
	[PromotionID] [char](12) NOT NULL,
	[AssetItemNumber] [int] NOT NULL,
	[ParentNumberAAID] [int] NOT NULL,
	[ShipToAttention] [char](50) NOT NULL,
	[PartnerAddressNumber] [int] NOT NULL,
	[PartnerContactLineNumberID] [int] NOT NULL,
	[CustomerContactLineNumberID] [int] NOT NULL,
	[ShipToCustContactLineNumID] [int] NOT NULL,
	[OpportunityNumber] [int] NOT NULL,
	[OrganizationStructureType] [char](3) NOT NULL,
	[UniqueKeyIDInternal] [int] NOT NULL,
	[CatalogName] [char](30) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDESOSalesOrderDetailHistory] PRIMARY KEY CLUSTERED 
(
	[OrderNumber] ASC,
	[OrderNumberDocumentCompany] ASC,
	[LineNumber] ASC,
	[OrderTypeCode] ASC,
	[OrderSuffix] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDESOSalesOrderDetailHistory] TO  SCHEMA OWNER 
GO
/****** Object:  Table [dbo].[JDESOSalesOrderDetail]    Script Date: 5/8/13 12:13:30 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JDESOSalesOrderDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[JDESOSalesOrderDetail](
	[SourceID] [int] NOT NULL,
	[Source] [char](20) NOT NULL,
	[OrderNumberDocumentCompany] [char](5) NOT NULL,
	[OrderNumber] [int] NOT NULL,
	[OrderTypeCode] [char](2) NOT NULL,
	[LineNumber] [decimal](20, 7) NOT NULL,
	[OrderSuffix] [char](3) NOT NULL,
	[BusinessUnitCode] [char](12) NOT NULL,
	[CompanyNumber] [char](5) NOT NULL,
	[OriginalOrderDocumentCompany] [char](5) NOT NULL,
	[OriginalOrderNumber] [char](8) NOT NULL,
	[OriginalOrderTypeCode] [char](2) NOT NULL,
	[OriginalLineNumber] [decimal](20, 7) NOT NULL,
	[RelatedOrderKeyCompany] [char](5) NOT NULL,
	[RelatedPoSoWoNumber] [char](8) NOT NULL,
	[RelatedPoSoWoType] [char](2) NOT NULL,
	[RelatedPOSOLineNumber] [decimal](20, 7) NOT NULL,
	[ContractNumber] [char](12) NOT NULL,
	[ContractSupplement] [int] NOT NULL,
	[ContractBalancesUpdated] [char](1) NOT NULL,
	[AddressNumber] [int] NOT NULL,
	[ShipToNumber] [int] NOT NULL,
	[ParentNumber] [int] NOT NULL,
	[RequestedDate] [datetime] NOT NULL,
	[TransactionDate] [datetime] NOT NULL,
	[PromisedDeliveryDate] [datetime] NOT NULL,
	[OriginalPromisedDate] [datetime] NOT NULL,
	[ActualDeliveryDate] [datetime] NOT NULL,
	[InvoiceDate] [datetime] NOT NULL,
	[CancelDate] [datetime] NOT NULL,
	[GLDate] [datetime] NOT NULL,
	[PromisedDelivery] [datetime] NOT NULL,
	[PriceEffectiveDate] [datetime] NOT NULL,
	[ShipDate] [datetime] NOT NULL,
	[FutureUseDate] [datetime] NOT NULL,
	[Reference1] [char](25) NOT NULL,
	[Reference2] [char](25) NOT NULL,
	[ItemNumber] [int] NOT NULL,
	[ItemNumber02] [char](25) NOT NULL,
	[ItemNumber03] [char](25) NOT NULL,
	[Location] [char](20) NOT NULL,
	[LotNumber] [char](30) NOT NULL,
	[FromGrade] [char](3) NOT NULL,
	[ThruGrade] [char](3) NOT NULL,
	[FromPotency] [decimal](20, 7) NOT NULL,
	[ThruPotency] [decimal](20, 7) NOT NULL,
	[DaysBeforeExpiration] [int] NOT NULL,
	[Description01] [char](30) NOT NULL,
	[Description02] [char](30) NOT NULL,
	[LineType] [char](2) NOT NULL,
	[StatusCodeNext] [char](3) NOT NULL,
	[StatusCodeLast] [char](3) NOT NULL,
	[HeaderBusinessUnit] [char](12) NOT NULL,
	[RelatedItemNumber] [char](8) NOT NULL,
	[KitMasterLineNumber] [decimal](20, 7) NOT NULL,
	[ComponentLineNumber] [decimal](20, 7) NOT NULL,
	[RelatedKitComponent] [int] NOT NULL,
	[NumberOfComponentPerParent] [decimal](22, 7) NOT NULL,
	[SalesCategory01Code] [char](3) NOT NULL,
	[SalesCategory02Code] [char](3) NOT NULL,
	[SalesCategory03Code] [char](3) NOT NULL,
	[SalesCategory04Code] [char](3) NOT NULL,
	[SalesCategory05Code] [char](3) NOT NULL,
	[PurchasingCategory01Code] [char](3) NOT NULL,
	[PurchasingCategory02Code] [char](3) NOT NULL,
	[PurchasingCategory03Code] [char](3) NOT NULL,
	[PurchasingCategory04Code] [char](3) NOT NULL,
	[PurchasingCategory05Code] [char](3) NOT NULL,
	[UnitOfMeasureAsInput] [char](2) NOT NULL,
	[QuantityOrdered] [decimal](22, 7) NOT NULL,
	[QuantityShipped] [decimal](22, 7) NOT NULL,
	[QuantityBackordered] [decimal](22, 7) NOT NULL,
	[QuantityCanceled] [decimal](22, 7) NOT NULL,
	[FutureQuantityCommitted] [decimal](22, 7) NOT NULL,
	[QuantityOpen] [decimal](22, 7) NOT NULL,
	[QuantityShippedToDate] [decimal](22, 7) NOT NULL,
	[QuantityRelieved] [decimal](22, 7) NOT NULL,
	[CommittedHS] [char](1) NOT NULL,
	[OtherQuantity] [char](1) NOT NULL,
	[UnitPrice] [decimal](20, 7) NOT NULL,
	[ExtendedPrice] [decimal](20, 7) NOT NULL,
	[AmountOpen] [decimal](20, 7) NOT NULL,
	[PriceOverrideCode] [char](1) NOT NULL,
	[TemporaryPrice] [char](1) NOT NULL,
	[EnteredUOMForUnitPrice] [char](2) NOT NULL,
	[UnitListPrice] [decimal](20, 7) NOT NULL,
	[UnitCost] [decimal](20, 7) NOT NULL,
	[ExtendedCost] [decimal](20, 7) NOT NULL,
	[CostOverrideCode] [char](1) NOT NULL,
	[TransferCost] [decimal](20, 7) NOT NULL,
	[PrintMessage] [char](10) NOT NULL,
	[PaymentTerms] [char](3) NOT NULL,
	[PaymentInstrument] [char](1) NOT NULL,
	[BasedonDate] [char](1) NOT NULL,
	[TradeDiscount] [decimal](20, 7) NOT NULL,
	[TradeDiscountOld] [decimal](20, 7) NOT NULL,
	[AdjustmentSchedule] [char](8) NOT NULL,
	[ItemPriceGroupCode] [char](8) NOT NULL,
	[PricingCategoryLevel] [char](3) NOT NULL,
	[DiscountFactor] [decimal](20, 7) NOT NULL,
	[DiscFactorTypeDollarOrPercent] [char](1) NOT NULL,
	[DiscountApplicationType] [char](1) NOT NULL,
	[CashDiscountPercent] [decimal](20, 7) NOT NULL,
	[DocumentCompany] [char](5) NOT NULL,
	[DocumentNumber] [int] NOT NULL,
	[DocumentType] [char](2) NOT NULL,
	[OriginalDocumentNumber] [int] NOT NULL,
	[OriginalDocumentTypeCode] [char](2) NOT NULL,
	[OriginalDocumentCompany] [char](5) NOT NULL,
	[PickSlipNumber] [int] NOT NULL,
	[DeliveryNumber] [int] NOT NULL,
	[PromotionNumber] [char](8) NOT NULL,
	[DraftNumber] [int] NOT NULL,
	[SalesTaxable] [char](1) NOT NULL,
	[TaxRateArea] [char](10) NOT NULL,
	[TaxExplanationCode] [char](2) NOT NULL,
	[AssociatedText] [char](1) NOT NULL,
	[PriorityProcessingCode] [char](1) NOT NULL,
	[PrintedCode] [char](1) NOT NULL,
	[BackOrdersAllowed] [char](1) NOT NULL,
	[SubstitutesAllowed] [char](1) NOT NULL,
	[PartialShipmentsAllowed] [char](1) NOT NULL,
	[LineOfBusiness] [char](3) NOT NULL,
	[EndUse] [char](3) NOT NULL,
	[DutyStatus] [char](2) NOT NULL,
	[CommodityCode] [char](15) NOT NULL,
	[NatureofTransaction] [char](2) NOT NULL,
	[PrimaryLastSupplierNumber] [int] NOT NULL,
	[BuyerNumber] [int] NOT NULL,
	[PreferredCarrierSales] [int] NOT NULL,
	[ModeOfTransportation] [char](3) NOT NULL,
	[ConditionsOfTransportation] [char](3) NOT NULL,
	[RouteCode] [char](3) NOT NULL,
	[StopCode] [char](3) NOT NULL,
	[ZoneNumber] [char](3) NOT NULL,
	[ContainerID] [char](20) NOT NULL,
	[FreightHandlingCode] [char](3) NOT NULL,
	[ApplyFreightYN] [char](1) NOT NULL,
	[ApplyFreight] [char](1) NOT NULL,
	[FreightCalculated] [char](1) NOT NULL,
	[RateCodeFreightMisc] [char](10) NOT NULL,
	[RateTypeFreightMisc] [char](1) NOT NULL,
	[ShippingCommodityClass] [char](3) NOT NULL,
	[ShippingConditionsCode] [char](3) NOT NULL,
	[LotSerialNumber] [char](30) NOT NULL,
	[UnitOfMeasurePrimary] [char](2) NOT NULL,
	[PrimaryQuantityOrdered] [decimal](22, 7) NOT NULL,
	[UnitOfMeasureSecondary] [char](2) NOT NULL,
	[SecondaryQuantityOrdered] [decimal](22, 7) NOT NULL,
	[UnitOfMeasurePricing] [char](2) NOT NULL,
	[UnitWeight] [decimal](20, 7) NOT NULL,
	[WeightUOM] [char](2) NOT NULL,
	[UnitVolume] [decimal](20, 7) NOT NULL,
	[VolumeUOM] [char](2) NOT NULL,
	[BasketRepriceGroup] [char](8) NOT NULL,
	[OrderRepriceGroup] [char](8) NOT NULL,
	[OrderRepricedIndicator] [char](1) NOT NULL,
	[InventoryCostingMethod] [char](2) NOT NULL,
	[CommitmentMethod] [char](1) NOT NULL,
	[GLOffset] [char](4) NOT NULL,
	[Century] [int] NOT NULL,
	[FiscalYear] [int] NOT NULL,
	[LineStatus] [char](2) NOT NULL,
	[SalesOrderStatus01] [char](1) NOT NULL,
	[SalesOrderStatus02] [char](1) NOT NULL,
	[SalesOrderStatus03] [char](1) NOT NULL,
	[SalesOrderStatus04] [char](1) NOT NULL,
	[SalesOrderStatus05] [char](1) NOT NULL,
	[SalesOrderStatus06] [char](1) NOT NULL,
	[SalesOrderStatus07] [char](1) NOT NULL,
	[SalesOrderStatus08] [char](1) NOT NULL,
	[SalesOrderStatus09] [char](1) NOT NULL,
	[SalesOrderStatus10] [char](1) NOT NULL,
	[SalesOrderStatus11] [char](1) NOT NULL,
	[SalesOrderStatus12] [char](1) NOT NULL,
	[SalesOrderStatus13] [char](1) NOT NULL,
	[SalesOrderStatus14] [char](1) NOT NULL,
	[SalesOrderStatus15] [char](1) NOT NULL,
	[SalespersonCode01] [int] NOT NULL,
	[SalespersonCommission01] [decimal](20, 7) NOT NULL,
	[SalespersonCode02] [int] NOT NULL,
	[SalespersonCommission02] [decimal](20, 7) NOT NULL,
	[ApplyCommission] [char](1) NOT NULL,
	[CommissionCategory] [char](8) NOT NULL,
	[ReasonCode] [char](3) NOT NULL,
	[GrossWeight] [decimal](20, 7) NOT NULL,
	[GrossWeightUOM] [char](2) NOT NULL,
	[AccountNumber] [char](29) NOT NULL,
	[AccountID] [char](8) NOT NULL,
	[PurchasingBusinessUnit] [char](12) NOT NULL,
	[ObjectAccount] [char](6) NOT NULL,
	[Subsidiary] [char](8) NOT NULL,
	[LedgerTypeCode] [char](2) NOT NULL,
	[SubLedger] [char](8) NOT NULL,
	[SubledgerType] [char](1) NOT NULL,
	[LocalTaxCode] [char](2) NOT NULL,
	[PriceCode1] [char](2) NOT NULL,
	[PriceCode2] [char](2) NOT NULL,
	[PriceCode3] [char](2) NOT NULL,
	[WarehouseStatusCode] [char](1) NOT NULL,
	[FreezeCode] [char](1) NOT NULL,
	[SendMethod] [char](1) NOT NULL,
	[CurrencyCode] [char](3) NOT NULL,
	[CurrencyConversionRateSpot] [decimal](20, 7) NOT NULL,
	[ForeignListPrice] [decimal](20, 7) NOT NULL,
	[ForeignUnitPrice] [decimal](20, 7) NOT NULL,
	[ForeignExtendedPrice] [decimal](20, 7) NOT NULL,
	[ForeignUnitCost2] [decimal](20, 7) NOT NULL,
	[ForeignExtendedCost] [decimal](20, 7) NOT NULL,
	[UserReservedCode] [char](2) NOT NULL,
	[UserReservedDate] [datetime] NOT NULL,
	[UserReservedAmount] [decimal](20, 7) NOT NULL,
	[UserReservedNumber] [int] NOT NULL,
	[UserReservedReference] [char](15) NOT NULL,
	[TransactionOriginator] [char](10) NOT NULL,
	[UserID] [char](10) NOT NULL,
	[ProgramID] [char](10) NOT NULL,
	[WorkStationID] [char](10) NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[TimeOfDay] [int] NOT NULL,
	[ManufacturingVarianceAcctFlag] [char](1) NOT NULL,
	[SalesOrderStatus17] [char](1) NOT NULL,
	[SalesOrderStatus18] [char](1) NOT NULL,
	[SalesOrderStatus19] [char](1) NOT NULL,
	[SalesOrderStatus20] [char](1) NOT NULL,
	[IntegrationReference01] [char](30) NOT NULL,
	[IntegrationReference02] [char](30) NOT NULL,
	[IntegrationReference03] [char](30) NOT NULL,
	[IntegrationReference04] [char](30) NOT NULL,
	[IntegrationReference05] [char](30) NOT NULL,
	[SourceofOrder] [int] NOT NULL,
	[Reference] [char](25) NOT NULL,
	[DemandUniqueKeyID] [int] NOT NULL,
	[PullSignal] [char](30) NOT NULL,
	[ReleaseNumber] [char](10) NOT NULL,
	[ScheduledShipmentTime] [int] NOT NULL,
	[TimeRelease] [int] NOT NULL,
	[DateRelease] [datetime] NOT NULL,
	[RequestedDeliveryTime] [int] NOT NULL,
	[ActualShipmentTime] [int] NOT NULL,
	[TimeOriginalPromisedDelivery] [int] NOT NULL,
	[TimeScheduledPick] [int] NOT NULL,
	[TimeFutureTime2] [int] NOT NULL,
	[CrossDockingFlag] [char](1) NOT NULL,
	[CrossDockingPriorityforSalesO] [decimal](28, 0) NOT NULL,
	[DualUnitOfMeasureItem] [char](1) NOT NULL,
	[BuyingSegmentCode] [char](10) NOT NULL,
	[CurrentBuyingSegmentCode] [char](10) NOT NULL,
	[ChangeOrderNumber] [int] NOT NULL,
	[AddressNumberDeliverTo] [int] NOT NULL,
	[PendingApprovalFlag] [char](1) NOT NULL,
	[RevisionReason] [char](6) NOT NULL,
	[MatrixControlLineNumber] [decimal](20, 7) NOT NULL,
	[ShipmentNumber] [int] NOT NULL,
	[PromisedDeliveryTime] [int] NOT NULL,
	[ProjectNumber] [int] NOT NULL,
	[SequenceNumber] [int] NOT NULL,
	[ItemRevisionLevel] [char](3) NOT NULL,
	[HoldOrdersCode] [char](2) NOT NULL,
	[BusinessUnitHeader] [char](12) NOT NULL,
	[BusinessUnitDemand] [char](12) NOT NULL,
	[CurrencyCodeBase] [char](3) NOT NULL,
	[DocumentLineNumberOriginal] [decimal](20, 7) NOT NULL,
	[CrossDockOrderCompanyOrderNum] [char](10) NOT NULL,
	[CrossDockOrderNo] [int] NOT NULL,
	[CrossDockOrderType] [char](4) NOT NULL,
	[CrossDockLineNumber] [decimal](20, 7) NOT NULL,
	[CrossDockOrderSuffix] [char](3) NOT NULL,
	[PortofEntryorExit] [char](6) NOT NULL,
	[PaymentTermsOverrideCode] [char](1) NOT NULL,
	[PromotionID] [char](12) NOT NULL,
	[AssetItemNumber] [int] NOT NULL,
	[ParentNumberAAID] [int] NOT NULL,
	[ShipToAttention] [char](50) NOT NULL,
	[PartnerAddressNumber] [int] NOT NULL,
	[PartnerContactLineNumberID] [int] NOT NULL,
	[CustomerContactLineNumberID] [int] NOT NULL,
	[ShipToCustContactLineNumID] [int] NOT NULL,
	[OpportunityNumber] [int] NOT NULL,
	[OrganizationStructureType] [char](3) NOT NULL,
	[UniqueKeyIDInternal] [int] NOT NULL,
	[CatalogName] [char](30) NOT NULL,
	[InsertIndicator] [int] NOT NULL,
	[InsertDate] [datetime] NOT NULL,
	[ChangeIndicator] [int] NOT NULL,
	[ChangeDate] [datetime] NOT NULL,
	[DeleteIndicator] [int] NOT NULL,
	[DeleteDate] [datetime] NOT NULL,
	[PurgeDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JDESOSalesOrderDetail] PRIMARY KEY CLUSTERED 
(
	[OrderNumber] ASC,
	[OrderNumberDocumentCompany] ASC,
	[LineNumber] ASC,
	[OrderTypeCode] ASC,
	[OrderSuffix] ASC,
	[SourceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
ALTER AUTHORIZATION ON [dbo].[JDESOSalesOrderDetail] TO  SCHEMA OWNER 
GO
USE [RapidReconcilerV5]
GO
/****** Object:  View [dbo].[vcr_F4101]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vcr_F4101]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vcr_F4101]
AS

SELECT     ItemNumber AS IMITM, ItemNumber02 AS IMLITM, Description01 AS IMDSC1, InventoryCostLevel AS IMCLEV, 0 AS IMUPMJ, 
                      UnitOfMeasurePrimary AS IMUOM1, SalesCategory01Code AS IMSRP1, SalesCategory02Code AS IMSRP2, SalesCategory03Code AS IMSRP3, 
                      SalesCategory04Code AS IMSRP4, SalesCategory05Code AS IMSRP5, SalesCategory06Code AS IMSRP6, SalesCategory07Code AS IMSRP7, 
                      SalesCategory08Code AS IMSRP8, SalesCategory09Code AS IMSRP9, SalesCategory10Code AS IMSRP0, GLCategory AS IMGLPT, 
                      StockingTypeCode AS IMSTKT
FROM          FB91DWCR2.dbo.JDEINItemMaster


' 
GO
ALTER AUTHORIZATION ON [dbo].[vcr_F4101] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Integrity12_Duplicate_Costs]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Integrity12_Duplicate_Costs]'))
EXEC dbo.sp_executesql @statement = N'


/****** Object:  View [dbo].[vv_Integrity11_CrossPeriods]    Script Date: 04/20/2011 08:28:26 ******/
CREATE View [dbo].[v_Integrity12_Duplicate_Costs] As
Select		Top 100 Percent
            COITM As ShortItem, COMCU As BranchPlant, COLOCN AS Location, COLOTN As Lot, COUNT(*) As Count
            FROM    dbo.F4105
            INNER JOIN dbo.vcr_F4101 ON (IMITM = COITM )
            Group By COITM, COMCU, COLOCN, COLOTN
            Having COUNT(*) > 1			 
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Integrity12_Duplicate_Costs] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Inventory_Companies]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Inventory_Companies]'))
EXEC dbo.sp_executesql @statement = N'CREATE View [dbo].[v_Inventory_Companies] As

Select CompanyNumber, MaxPeriodEnds from RCompanies' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Inventory_Companies] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Last_Elapsed_Period_End]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Last_Elapsed_Period_End]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.v_Last_Elapsed_Period_End    Script Date: 4/20/2007 3:46:06 PM ******/

CREATE  VIEW [dbo].[v_Last_Elapsed_Period_End]
AS  
	Select 	A.CompanyNumber, Max(A.PeriodEnds) As PeriodEnds
	From	RFiscalCalendar A,
	(Select C.CompanyNumber, Max(PeriodEnds) As PeriodEnds
	 From RFiscalCalendar C
	 Inner Join v_Inventory_Companies D On C.CompanyNumber = D.CompanyNumber
	 Group by C.CompanyNumber) As B
Where	A.CompanyNumber = B.CompanyNumber And A.PeriodEnds < B.PeriodEnds
Group By A.CompanyNumber

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Last_Elapsed_Period_End] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vcr_F0901]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vcr_F0901]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vcr_F0901]
AS

SELECT		A.CompanyNumber AS GMCO, AccountID AS GMAID, BusinessUnitCode AS GMMCU, Object AS GMOBJ, Subsidiary AS GMSUB, Description01 AS GMDL01
FROM        FB91DWCR2.dbo.JDEGAAccountMaster A
WHERE		A.Object IN (select distinct ObjectAccount from FB91DWCR2.dbo.JDEIBDistributionMFGAAIValue)
' 
GO
ALTER AUTHORIZATION ON [dbo].[vcr_F0901] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Master_Accounts]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Master_Accounts]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View [dbo].[v_Master_Accounts]    Script Date: 02/07/2009 11:22:48 ******/
CREATE View [dbo].[v_Master_Accounts] As
Select	GMAID As ShortAccount,
		CASE WHEN ( GMSUB = '''' OR  GMSUB IS NULL ) 
			 THEN LTRIM(GMMCU + ''.'' + GMOBJ)
			 ELSE LTRIM(GMMCU + ''.'' + GMOBJ + ''.'' + GMSUB) End As LongAccount
From	vcr_F0901

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Master_Accounts] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vcr_F4801]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vcr_F4801]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vcr_F4801]
AS

SELECT DISTINCT 
                      B.CompanyNumber AS WACO, Branch AS WAMMCU, A.BusinessUnitCode AS WAMCU, OrderTypeCode AS WADCTO, OrderNumber AS WADOCO, 
                      StatusCodeWO AS WASRST, StatusComment AS WASTCM, TransactionDate AS WATRDJ
FROM				  FB91DWCR2.dbo.JDEWOWorkOrderMasterFile A
INNER JOIN			  FB91DWCR2.dbo.JDEGSBusinessUnitMaster B ON (Branch = B.BusinessUnitCode)

' 
GO
ALTER AUTHORIZATION ON [dbo].[vcr_F4801] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Report1_Open_Mfg]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Report1_Open_Mfg]'))
EXEC dbo.sp_executesql @statement = N'---------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------
-- VIEWS
---------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[v_Report1_Open_Mfg]
AS  SELECT
            B.CompanyNumber AS Company,
            B.PeriodEnds,
			ial.BusinessUnit,
            B.LongAccount,
            B.BranchPlant,
            B.OrderType,
            B.DocType,
            B.DocNumber,
            B.TransactionAmount AS Variance,
            B.Status AS OrderStatus,
            LTRIM(WAMCU) AS Charge_To_CC
    FROM    RUnPostedCardex B 
    INNER JOIN RCompanies C
            ON ( B.CompanyNumber = C.CompanyNumber AND
                 B.PeriodEnds <= C.MaxPeriodEnds ) 
    Left Outer JOIN vcr_F4801
            ON ( WACO = B.CompanyNumber AND
                 WADOCO = DocNumber )
		inner join dbo.RInvAccountList ial
					on b.companynumber = ial.companynumber
					and b.longaccount = ial.longaccount
    WHERE   DocType IN ( ''IC'', ''IM'',''LC'',''LM'' ) AND
            B.TransactionAmount <> 0 AND
            B.LongAccount Not In (''Outside Operations'', ''GL CLass Not In Base Table'')
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Report1_Open_Mfg] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Integrity7_Frozen_Cost]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Integrity7_Frozen_Cost]'))
EXEC dbo.sp_executesql @statement = N'

CREATE VIEW [dbo].[v_Integrity7_Frozen_Cost]
AS  SELECT TOP 100 PERCENT
            CompanyNumber AS Company,
            BranchPlant,
            ItemNumber,
			IMSTKT As ST,
            Location,
            Lot,
			Sum(QuantityOnHand) As QOH,
            UnitCost,
            CONVERT(DECIMAL(18, 6), ( Material + Labor + Overhead )) AS FrzCost,
            UnitCost - CONVERT(DECIMAL(18, 4), ( Material + Labor + Overhead )) AS Variance
    FROM    RPerpetualInv
	Left Outer Join vcr_F4101 ON (ShortItem = IMITM)
    WHERE   CostMethod = ''07'' AND IMSTKT Not In (''K'', ''C'') And ItemNumber Not Like ''%*OP%'' And
            ABS(UnitCost - CONVERT(DECIMAL(18, 4), ( Material + Labor + Overhead ))) > .01
	Group By CompanyNumber,
            BranchPlant,
            ItemNumber,
			IMSTKT,
			UnitCost,
            Location,
            Lot,
			Material,
			Labor,
			OverHead
    ORDER BY CompanyNumber,
            BranchPlant,
            ItemNumber,
            Location,
            Lot
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Integrity7_Frozen_Cost] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vcr_F41002]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vcr_F41002]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vcr_F41002]
AS
SELECT     BusinessUnitCode AS UMMCU, ItemNumber AS UMITM, UnitOfMeasure AS UMUM, RelatedUnitOfMeasure AS UMRUM, 
                      UnitOfMeasureStructure AS UMUSTR, ConversionFactor AS UMCONV, ConvFactorSecondaryToPrimary AS UMCNV1
FROM          FB91DWCR2.dbo.JDEINUOMConversionFactors

' 
GO
ALTER AUTHORIZATION ON [dbo].[vcr_F41002] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_UOM_CONV]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_UOM_CONV]'))
EXEC dbo.sp_executesql @statement = N'CREATE View [dbo].[v_UOM_CONV] As

Select Distinct
		IMITM As ShortItem,
		IMLITM As Item,
		UMMCU As Branch,
		UMUM As TransUOM,
		Convert(Float,UMCNV1) As Factor,
		IMUOM1 As PrimaryUOM
From	vcr_F41002
Inner Join	vcr_F4101 On (UMITM = IMITM)
Where	UMUM <> IMUOM1 -- And UMUSTR = ''''
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_UOM_CONV] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_UOM_CONV_Rev]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_UOM_CONV_Rev]'))
EXEC dbo.sp_executesql @statement = N'

CREATE View [dbo].[v_UOM_CONV_Rev] As
Select Distinct
		IMITM As ShortItem,
		IMLITM As Item,
		UMMCU As Branch,
		UMRUM As TransUOM,
		Convert(Float,((1/UMCONV)*UMCNV1)) As Factor,
		IMUOM1 As PrimaryUOM
From	vcr_F41002
Inner Join	vcr_F4101 On (UMITM = IMITM)
Where	UMRUM <> IMUOM1 And UMCONV <> 0 --And UMUSTR = ''''
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_UOM_CONV_Rev] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vcr_F41003]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vcr_F41003]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vcr_F41003]
AS
SELECT     UnitOfMeasure AS UCUM, RelatedUnitOfMeasure AS UCRUM, ConversionFactor AS UCCONV
FROM          FB91DWCR2.dbo.JDEINUOMstandardConversion

' 
GO
ALTER AUTHORIZATION ON [dbo].[vcr_F41003] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_UOM_STD_Single]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_UOM_STD_Single]'))
EXEC dbo.sp_executesql @statement = N'CREATE View [dbo].[v_UOM_STD_Single] As

Select Distinct
		UCUM As TransUOM,
		Convert(Decimal(18,6),UCCONV) As Factor,
		UCRUM As PrimaryUOM
From	vcr_F41003

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_UOM_STD_Single] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vcr_F30026]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vcr_F30026]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vcr_F30026]
AS

SELECT DISTINCT 
                      CC.Branch AS IEMMCU, CC.ItemNumber AS IEITM, CC.ItemNumber02 AS IELITM, CC.Location AS IELOCN, CC.LotNumber AS IELOTN, CC.CostMethodCode AS IELEDG, 
                      CC.CostType AS IECOST, CC.ManufacturedCostFrozen AS IESTDC, CC.ManufacturedCostSimulated AS IEXSMC, CC.CostRollupFrozen AS IECSL, 
                      CC.CostRollupSimulated AS IEXSCR, 0 AS Formatted
FROM				FB91DWCR2.dbo.JDEPDItemCostComponent CC
--INNER JOIN			FB91DWCR2.dbo.JDEINCostLedger CL ON (
--											CC.Branch = CL.BusinessUnitCode 
--											AND CC.ItemNumber = CL.ItemNumber 	
--											AND CC.Location = CL.Location
--											AND CC.LotNumber = CL.LotNumber
--											AND CC.CostMethodCode = CL.CostMethodCode)
WHERE CC.CostMethodCode = ''07'' --CL.InventoryCostingSelection = ''I''

' 
GO
ALTER AUTHORIZATION ON [dbo].[vcr_F30026] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Costs_Labor]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Costs_Labor]'))
EXEC dbo.sp_executesql @statement = N'

CREATE   VIEW [dbo].[v_Costs_Labor]
AS

	SELECT  IEMMCU 		AS ''BranchPlant'',
            	IEITM 		AS ''ShortItem'',
            	IELOCN 		AS ''Location'',
            	IELOTN 		AS ''Lot'',
            	SUM(IECSL) 	AS ''Cost''
    	FROM    vcr_F30026
    	WHERE   IECOST LIKE ''B%''
    	GROUP BY IEMMCU, IEITM, IELOCN, IELOTN


' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Costs_Labor] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_UOM_STD_Single_R]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_UOM_STD_Single_R]'))
EXEC dbo.sp_executesql @statement = N'
CREATE View [dbo].[v_UOM_STD_Single_R] As
Select Distinct
		UCRUM As TransUOM,
		Convert(Decimal(18,6), (1/UCCONV)) As Factor,
		UCUM As PrimaryUOM
From	vcr_F41003
Where	UCCONV <> 0
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_UOM_STD_Single_R] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Costs_Material]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Costs_Material]'))
EXEC dbo.sp_executesql @statement = N'

CREATE   VIEW [dbo].[v_Costs_Material]
AS
	SELECT  IEMMCU 		AS ''BranchPlant'',
            	IEITM 		AS ''ShortItem'',
            	IELOCN 		AS ''Location'',
            	IELOTN 		AS ''Lot'',
            	SUM(IECSL) 	AS ''Cost''
    	FROM    vcr_F30026
    	WHERE   IECOST NOT LIKE ''B%'' AND IECOST NOT LIKE ''C%''
    	GROUP BY IEMMCU, IEITM, IELOCN, IELOTN


' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Costs_Material] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_UOM_STD_Double]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_UOM_STD_Double]'))
EXEC dbo.sp_executesql @statement = N'


CREATE View [dbo].[v_UOM_STD_Double] As

Select Distinct
		A.UCUM As TransUOM,
		Convert(Decimal(18,6),(B.UCCONV * A.UCCONV)) As Factor,
		B.UCRUM As PrimaryUOM
From	vcr_F41003 A
Inner Join	vcr_F41003 B On (A.UCRUM = B.UCUM)

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_UOM_STD_Double] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Costs_Overhead]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Costs_Overhead]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Costs_Overhead]
AS
SELECT  IEMMCU AS ''BranchPlant'',
            IEITM AS ''ShortItem'',
            IELOCN AS ''Location'',
            IELOTN AS ''Lot'',
            SUM(IECSL) AS ''Cost''
    FROM    vcr_F30026
    WHERE   ( IECOST LIKE ''C%'' )
    GROUP BY IEMMCU,
            IEITM,
            IELOCN,
            IELOTN
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Costs_Overhead] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vcr_F0006]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vcr_F0006]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vcr_F0006]
AS

SELECT		A.CompanyNumber AS MCCO, A.BusinessUnitCode AS MCMCU, ProjectNumber AS MCMCUS
FROM         FB91DWCR2.dbo.JDEGSBusinessUnitMaster  A


' 
GO
ALTER AUTHORIZATION ON [dbo].[vcr_F0006] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_GL_Classes_Used]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_GL_Classes_Used]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_GL_Classes_Used]
AS  SELECT DISTINCT
            MCCO,
            LIGLPT
    FROM    vcr_F0006 A 
    INNER JOIN F41021 B
            ON ( A.MCMCU = B.LIMCU )
    WHERE   LIGLPT <> '''' AND
            LIPQOH <> 0

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_GL_Classes_Used] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Diagnostic1_Capture]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Diagnostic1_Capture]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Diagnostic1_Capture]
AS
-- Diagnostic Report 1

SELECT TOP 100 PERCENT
            StartTime,
            RunDate AS ''Capture Complete'',
            Companies,
            Accounts,
            Baseline AS BaselineCount,
            Locations,
            Cardex AS CardexCount,
            GL AS GLCount,
            BalCXVar AS CardexBalVariance,
            OOBalance AS OutofBalance,
            Warnings,
            Errors,
            DaysBack
    FROM    dbo.RunHistory
    ORDER BY Counter DESC

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Diagnostic1_Capture] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Diagnostic2_Error]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Diagnostic2_Error]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Diagnostic2_Error]
AS
SELECT TOP 1000
            Convert(Varchar(25),Time1) AS ''StartTime'',
            Step,
            Process,
            UpdateCount,
            ErrorNum,
            Error
    FROM    RServer_Log
    WHERE   Counter >= ( SELECT MAX(Counter)
                         FROM   RServer_Log
                         WHERE  Process = ''New Cycle Started'' ) AND
            ( ErrorNum <> 0 )
    ORDER BY Counter DESC
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Diagnostic2_Error] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Diagnostic3_Server]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Diagnostic3_Server]'))
EXEC dbo.sp_executesql @statement = N'

CREATE VIEW [dbo].[v_Diagnostic3_Server]
AS
SELECT      Top 10000
			A.Time1 As Time,
            A.Step,
            Case When A.Process Is Null Then '''' Else A.Process End As Process,
            A.UpdateCount,
            A.Error,
            A.ErrorNum
FROM		RServer_Log A

ORDER BY	A.Time1 DESC


' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Diagnostic3_Server] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Diagnostic4_Config]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Diagnostic4_Config]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Diagnostic4_Config]
AS
SELECT TOP 1000
            Convert(Varchar(25),Time1) AS ''StartTime'',
            Step,
            Process
    FROM    RServer_Log
    WHERE   Step IN ( ''Company'', ''Constants'', ''Users'' )
    ORDER BY Counter DESC
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Diagnostic4_Config] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Diagnostic5_Netting]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Diagnostic5_Netting]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[v_Diagnostic5_Netting] As

Select Top 100 Percent Comment, Count(*) As ''Count'', Sum(CardexLedgerVariance) As ''Variance''
From RCardexLedgerCompare2
Where Status = ''Document Match''
Group By Status, Comment
Order By Status, Comment' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Diagnostic5_Netting] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Diagnostic6_Validation]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Diagnostic6_Validation]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Diagnostic6_Validation]
AS  SELECT  RValidation.TableNumber,
            RValidation.Category,
            RValidation.OnHandQty,
            RValidation.OnHandAmount,
            RValidation.CardexAmount,
            RValidation.GLAmount
    FROM    dbo.RValidation

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Diagnostic6_Validation] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Diagnostic7_Variance]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Diagnostic7_Variance]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Diagnostic7_Variance]
AS  SELECT TOP 100 PERCENT
            A.CompanyNumber AS Company,
            A.PeriodEnds,
            CASE WHEN Status IN ( ''Sales Update Required'',
                                  ''Mfg Accounting Required'' ) THEN ''In Process''
                 WHEN Status IN ( ''Manual Entry'', ''Document Match'', ''Green'' ) THEN ''Reconciled''
                 ELSE ''UnReconciled''
            END AS ''Type'',
            A.Status,
            A.DocType,
            A.OrderType,
            SUM(A.CardexLedgerVariance) AS Variance,
            COUNT(*) AS DocumentCount
    FROM    RCardexLedgerCompare A
	INNER JOIN RCompanies c On (A.CompanyNumber = c.CompanyNumber)
    WHERE   InventoryAccount <> ''Outside Operations''
    GROUP BY A.CompanyNumber,
            A.PeriodEnds,
            A.Status,
            A.DocType,
            A.OrderType
    ORDER BY A.CompanyNumber,
            A.PeriodEnds DESC,
            Type,
            A.Status,
            A.DocType,
            A.OrderType


' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Diagnostic7_Variance] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Integrity1_AAI_Base]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Integrity1_AAI_Base]'))
EXEC dbo.sp_executesql @statement = N'

CREATE VIEW [dbo].[v_Integrity1_AAI_Base]
AS  SELECT DISTINCT TOP 100 PERCENT
            dbo.RAccountInstr.CompanyNumber AS Company,
            dbo.RAccountInstr.TableNumber AS AAITable,
            dbo.RAccountInstr.DocType,
            dbo.RAccountInstr.GLClass,
            dbo.RAccountInstr.LongAccount AS Account,
            dbo.RAccountInstr.Comment AS Recommendation
    FROM    dbo.RAccountInstr,
            dbo.RConstants Const,
            ( SELECT DISTINCT
                        A.CompanyNumber,
                        GLClass,
                        SUM(OnHandVariance) AS Variance
              FROM      RInvLedgerClasses A
			  INNER JOIN RCompanies c On (a.CompanyNumber = c.CompanyNumber)
              GROUP BY  A.CompanyNumber,
                        GLClass ) AS T
    WHERE   dbo.RAccountInstr.TableNumber = Const.AAITableNum AND
            dbo.RAccountInstr.DocType = Const.AAIDocType AND
            dbo.RAccountInstr.CompanyNumber = T.CompanyNumber AND
            dbo.RAccountInstr.GLClass = T.GLClass
    ORDER BY dbo.RAccountInstr.CompanyNumber,
            dbo.RAccountInstr.TableNumber,
            dbo.RAccountInstr.DocType,
            dbo.RAccountInstr.GLClass,
            dbo.RAccountInstr.LongAccount


' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Integrity1_AAI_Base] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Integrity10_Duplicate_Sales]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Integrity10_Duplicate_Sales]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Integrity10_Duplicate_Sales]
AS  SELECT TOP 100 PERCENT
	A.CompanyNumber As Company, InventoryAccount, PeriodEnds, DocType, DocNumber, OrderType
	From RCardexLedgerCompare2 A
	INNER JOIN RCompanies c On (A.CompanyNumber = c.CompanyNumber)
	Where Comment = ''Multiple Shipments in Cardex''
	Order By A.CompanyNumber, InventoryAccount, PeriodEnds Desc

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Integrity10_Duplicate_Sales] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Integrity11_CrossPeriods]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Integrity11_CrossPeriods]'))
EXEC dbo.sp_executesql @statement = N'


/****** Object:  View [dbo].[vv_Integrity11_CrossPeriods]    Script Date: 04/20/2011 08:28:26 ******/
CREATE View [dbo].[v_Integrity11_CrossPeriods] As
Select		Top 100 Percent
			B.PeriodEnds As ''TransPer(To)'', 
			A.PeriodEnds As ''GLPer(From)'',
			Cast(ILKCO As nvarchar(5)) As Company, 
			Cast(InventoryAccount As nvarchar(30)) As Account,
			ILDCT As DT,
			--Cast(ILTRDJ As NVarchar(11)) As TransDate, 
			Cast(ILLITM As nvarchar(29)) AS ILLITM,  
			SUM(CAST(ILTRQT As Decimal(18,2))) As Units, 
			SUM(CAST(ILPAID As Decimal(18,2))) as Amount
		
From		F4111B A
Inner Join	RPeriodEnds B On (ILKCO = CompanyNumber And ILTRDJ = CDATE)
Inner Join	RInvAccountList On (InventoryAccount = LongAccount)
Where		BusinessUnit <> '''' And B.PeriodEnds <> A.PeriodEnds
Group by	B.PeriodEnds, A.PeriodEnds, ILKCO, InventoryAccount, ILDCT, ILLITM 
Order By	B.PeriodEnds, A.PeriodEnds, ILKCO, InventoryAccount, ILDCT, ILLITM 
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Integrity11_CrossPeriods] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Integrity2_AAI_Discrp]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Integrity2_AAI_Discrp]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Integrity2_AAI_Discrp]
AS  SELECT TOP 100 PERCENT
            A.CompanyNumber AS Company,
            TableNumber,
            DocType,
            GLClass,
            BaseAccount AS AAI_Base,
            CurrentAccount AS Discr_Account,
            Comment
    FROM    RAAIDiscr A
	INNER JOIN RCompanies c On (A.CompanyNumber = c.CompanyNumber)
    ORDER BY A.CompanyNumber,
            TableNumber,
            DocType,
            GLClass

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Integrity2_AAI_Discrp] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Integrity3_QOH]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Integrity3_QOH]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Integrity3_QOH]
AS  SELECT TOP 100 PERCENT
            PP.CompanyNumber AS ''Company'',
            PP.GLClass AS ''GL Class'',
            LTRIM(PP.BranchPlant) AS ''Branch'',
            PP.ItemNumber AS ''Item'',
            PP.ItemDescription AS ''Description'',
            PP.Location AS ''Location'',
            PP.Lot AS ''Lot'',
            CAST(PP.QuantityonHand AS DECIMAL(18, 2)) AS ''Quantity'',
            CAST(PP.UnitCost AS DECIMAL(18, 4)) AS ''Cost'',
            CAST(PP.UnitCost * PP.QuantityonHand AS DECIMAL(18, 2)) AS Variance
    FROM    dbo.RPerpetualInv PP 
    INNER JOIN dbo.RCompanies Comp
            ON ( PP.CompanyNumber = Comp.CompanyNumber )
    WHERE   PP.LongAccount = ''GL Class not in Base Table'' AND
            ABS(CAST(PP.UnitCost * PP.QuantityonHand AS DECIMAL(18, 2))) > .50
    ORDER BY PP.CompanyNumber,
            PP.BranchPlant,
            PP.ItemNumber,
            PP.Location,
            PP.Lot

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Integrity3_QOH] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Integrity3A_CX]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Integrity3A_CX]'))
EXEC dbo.sp_executesql @statement = N'CREATE View [dbo].[v_Integrity3A_CX] As
Select	Top 100 Percent
		ILKCO as Company,
		ILGLPT AS GLClass,
		Max(PeriodEnds) As ''Last Period Used'',
		Convert(Decimal(18,2),Sum(ILPAID)) As Variance
From	F4111B
INNER JOIN RCompanies c On (ILKCO = c.CompanyNumber)
Where	InventoryAccount = ''GL Class not in Base Table''
Group By	ILKCO, ILGLPT
Order By	ILKCO, ILGLPT' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Integrity3A_CX] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Integrity4_UOM_Conv]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Integrity4_UOM_Conv]'))
EXEC dbo.sp_executesql @statement = N'

CREATE VIEW [dbo].[v_Integrity4_UOM_Conv]
AS
SELECT DISTINCT TOP 100 PERCENT
			ILKCO As Company, 
			ILMCU As BranchPlant,
			ILITM As ShortItem, 
			ILLITM As ItemNumber, 
			ILTRUM As TransUOM, 
			UnitofMeasure As PrimeUOM
            FROM    dbo.F4111B With (NOLOCK)
			INNER JOIN RCompanies c On (ILKCO = c.CompanyNumber)
            INNER JOIN RPerpetualInv On (BranchPlant = ILMCU And ShortItem = dbo.F4111B.ILITM And Location = ILLOCN And Lot = ILLOTN)
WHERE   dbo.F4111B.PrimeFlag = ''N'' AND ILTRUM <> ''  ''

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Integrity4_UOM_Conv] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Integrity5_GL_Class]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Integrity5_GL_Class]'))
EXEC dbo.sp_executesql @statement = N'

CREATE VIEW [dbo].[v_Integrity5_GL_Class]
AS  SELECT TOP 100 PERCENT
            CompanyNumber AS Company,
            BranchPlant AS ''Branch'',
            ItemNumber AS ''Item Number'',
			ItemDescription As ''Desc'',
            Location AS ''Location'',
            Lot AS ''Lot'',
            StockingType AS ''Stock Type'',
            GLClass AS ''Branch Class'',
            LIGLPT AS ''Location Class''
    FROM    RPerpetualInv
    INNER JOIN dbo.F41021 ON ( LIMCU = BranchPlant AND LIITM = ShortItem And LILOCN = Location And LILOTN = Lot ) 
    WHERE   GLClass <> LIGLPT
    ORDER BY CompanyNumber, BranchPlant, ItemNumber


' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Integrity5_GL_Class] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Integrity9_Sales_Cardex]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Integrity9_Sales_Cardex]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Integrity9_Sales_Cardex]
AS  SELECT TOP 100 PERCENT
	A.CompanyNumber As Company, InventoryAccount, PeriodEnds, DocType, DocNumber, OrderType
	From RCardexLedgerCompare2 A
    Inner Join RCompanies c On (A.CompanyNumber = C.CompanyNumber) 
	Where Comment = ''Cardex missing sales line''
	Order By A.CompanyNumber, InventoryAccount, PeriodEnds Desc

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Integrity9_Sales_Cardex] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Landed_Costs]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Landed_Costs]'))
EXEC dbo.sp_executesql @statement = N'CREATE View [dbo].[v_Landed_Costs] As
Select	ILKCO As CompanyNumber,
		InventoryAccount,
		PeriodEnds,
		ILDCT As DocType,
		ILDOC As DocNumber,
		ILDCTO As OrderType,
		Cast(Sum(ILPAID) as Decimal(18,2)) As Amount
From	F4111B
Where	ILTREX = ''Landed Cost                   ''
Group By	ILKCO, InventoryAccount, PeriodEnds, ILDCT, ILDOC, ILDCTO
Having		Abs(Sum(ILPAID)) > 1


' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Landed_Costs] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Lean_Xref]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Lean_Xref]'))
EXEC dbo.sp_executesql @statement = N'CREATE View [dbo].[v_Lean_Xref] As
Select Distinct SDDOC As GL, SDDOCO As Cardex From F3106 Where SDJOBN = ''LEAN''

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Lean_Xref] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Net_Intercompany_Transactions]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Net_Intercompany_Transactions]'))
EXEC dbo.sp_executesql @statement = N'Create View [dbo].[v_Net_Intercompany_Transactions] As
Select A.InventoryAccount, A.PeriodEnds, A.DocType, A.DocNumber
From	RCardexLedgerCompare2 A
Inner Join	RCardexLedgerCompare2 B On(A.InventoryAccount = B.InventoryAccount And A.PeriodEnds = B.PeriodEnds And A.DocType = B.DocType And A.DocNumber = B.DocNumber)
Where A.CompanyNumber <> B.CompanyNumber
Group By A.InventoryAccount, A.PeriodEnds, A.DocType, A.DocNumber
Having Sum(A.CardexLedgerVariance + B.CardexLedgerVariance) = 0
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Net_Intercompany_Transactions] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Net_Matched_Transactions]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Net_Matched_Transactions]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Net_Matched_Transactions]
AS
SELECT			CompanyNumber, InventoryAccount, PeriodEnds, MatchingDocument, MatchingType
    FROM		RCardexLedgerCompare2
	Inner Join	RConstants On (1=1)
    Where		MatchingDocument > 0 And MatchingType <> ''''
    GROUP BY	CompanyNumber, InventoryAccount, PeriodEnds, MatchingDocument, MatchingType, Threshold1
    HAVING		ABS(SUM(CardexLedgerVariance)) < Threshold1
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Net_Matched_Transactions] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Net_Rate_Based_WO]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Net_Rate_Based_WO]'))
EXEC dbo.sp_executesql @statement = N'CREATE View [dbo].[v_Net_Rate_Based_WO] As
Select	CompanyNumber,
		InventoryAccount,
		PeriodEnds,
		OrderType,
		DocType,
		MfgBatch,
		Sum(CardexLedgerVariance) As Variance
 
From	RCardexLedgerCompare2 
Inner Join RConstants On (1=1)
Where	OrderType = ''RS'' And Status = ''Red''

Group By CompanyNumber,
		InventoryAccount,
		PeriodEnds,
		OrderType,
		DocType,
		MfgBatch,
		Threshold1

Having	abs(Sum(CardexLedgerVariance)) < Threshold1

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Net_Rate_Based_WO] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Net_Work_Order_XRef]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Net_Work_Order_XRef]'))
EXEC dbo.sp_executesql @statement = N'CREATE View [dbo].[v_Net_Work_Order_XRef] As


Select		Companynumber,
		InventoryAccount,
		PeriodEnds,
		MatchingDocument,
		MatchingType,
		MfgBatch
From		RCardexLedgerCompare2
Inner Join	RConstants On (1=1)
Where		DocType In (''IC'',''IM'',''LC'',''LM'') And MatchingDocument > 0
Group By	Companynumber,
		InventoryAccount,
		PeriodEnds,
		MatchingDocument,
		MatchingType,
		MfgBatch,
		Threshold1
Having		Abs(Sum(CardexLedgerVariance)) <= Threshold1

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Net_Work_Order_XRef] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Notes_by_User]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Notes_by_User]'))
EXEC dbo.sp_executesql @statement = N'CREATE View [dbo].[v_Notes_by_User] As
Select		Top 100 Percent A.*
From		RCardexLedgerCompare2WorkNote A
Inner Join  RCardexLedgerCompare2 B On (A.CompanyNumber = B.CompanyNumber and A.InventoryAccount = B.InventoryAccount And A.PeriodEnds = B.PeriodEnds And A.DocType = B.DocType And A.DocNumber = B.DocNumber And A.MfgBatch = B.MfgBatch)
Where		A.InventoryAccount <> ''GL CLass not in Base Table''
Order By	LastModifiedBy, LastModifiedDate
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Notes_by_User] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Outside_Operation_GLClasses]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Outside_Operation_GLClasses]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Outside_Operation_GLClasses]
AS  SELECT DISTINCT
            CompanyNumber,
            GLClass
    FROM    RPerpetualInv
    WHERE   ItemNumber LIKE ''%*OP%'' AND
            GLClass <> ''''


' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Outside_Operation_GLClasses] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Outside_Operation_Issues]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Outside_Operation_Issues]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Outside_Operation_Issues]
AS  SELECT  CompanyNumber,
            InventoryAccount,
            PeriodEnds,
            OrderType,
            DocType,
            DocNumber,
            MatchingDocument,
            SUM(CardexLedgerVariance) AS CardexLedgerVariance
    FROM    RCardexLedgerCompare2
    WHERE   DocType = ''IM'' AND
            InventoryAccount = ''Outside Operations''
    GROUP BY CompanyNumber,
            InventoryAccount,
            PeriodEnds,
            OrderType,
            DocType,
            DocNumber,
            MatchingDocument
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Outside_Operation_Issues] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Outside_Operation_Receipts]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Outside_Operation_Receipts]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Outside_Operation_Receipts]
AS  SELECT TOP 100 PERCENT
            CompanyNumber,
            A.InventoryAccount,
            A.PeriodEnds,
            DocType,
            DocNumber,
            OrderType,
            ILDOCO AS ''PO'',
            SUM(CardexLedgerVariance) AS CardexLedgerVariance
    FROM    RCardexLedgerCompare2 A 
    INNER JOIN F4111B B
            ON ( ILKCO = CompanyNumber AND
                 A.InventoryAccount = B.InventoryAccount AND
                 A.PeriodEnds = B.PeriodEnds AND
                 A.DocType = B.ILDCT AND
                 A.DocNumber = B.ILDOC )
    WHERE   DocType = ''OV'' AND
            A.InventoryAccount = ''Outside Operations'' AND
            A.Status NOT IN ( ''Document Match'', ''Green'' )
    GROUP BY CompanyNumber,
            A.InventoryAccount,
            A.PeriodEnds,
            DocType,
            DocNumber,
            OrderType,
            ILDOCO
    ORDER BY DocNumber ASC
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Outside_Operation_Receipts] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Report2_Open_Sales]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Report2_Open_Sales]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[v_Report2_Open_Sales]
AS  SELECT 
            B.CompanyNumber AS Company,
            B.PeriodEnds,
			ial.BusinessUnit,
            B.LongAccount,
            B.BranchPlant,
            B.DocType AS OrderType,
            B.DocNumber AS OrderNumber,
            B.TransactionAmount AS Variance,
            B.Status AS OrderStatus
    FROM    RUnPostedCardex B 
    INNER JOIN RCompanies C
            ON ( B.CompanyNumber = C.CompanyNumber AND
                 B.PeriodEnds <= C.MaxPeriodEnds )
		inner join dbo.RInvAccountList ial
					on b.companynumber = ial.companynumber
					and b.longaccount = ial.longaccount
    WHERE   DocType NOT IN ( ''IC'', ''IM'',''LC'',''LM'') And 
			ial.longaccount not in (''GL Class Not In Base Table'',''Outside Operations'') And
			B.TransactionAmount <> 0
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Report2_Open_Sales] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Report3_Open_Batches]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Report3_Open_Batches]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Report3_Open_Batches]
AS  
	SELECT
            B.CompanyNumber AS Company,
            B.PeriodEnds,
			ial.BusinessUnit,
            B.LongAccount,
            B.BatchType,
            B.BatchNumber AS Batch,
            Cast(B.OpenAmount As Decimal(18,2)) AS Amount,
            B.UserName,
			App As Approval_Status,
            Post AS Posting_Status
    FROM    dbo.RUnpostedBatches B 
    INNER JOIN RCompanies A ON ( B.CompanyNumber = A.CompanyNumber AND B.PeriodEnds <= A.MaxPeriodEnds ) 
	INNER JOIN RInvAccountList ial ON (b.companynumber = ial.companynumber and b.longaccount = ial.longaccount)
    WHERE   B.OpenAmount <> 0
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Report3_Open_Batches] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Report4_GL_Roll_Forward]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Report4_GL_Roll_Forward]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Report4_GL_Roll_Forward]
AS
SELECT 
            A.CompanyNumber AS Company,
            A.LongAccount,
			ial.BusinessUnit,
            A.PeriodEnds,
            A.BeginningBalance AS Beg_Bal,
            A.PeriodGL,
            A.EndingGLBalance AS Calc_End_Bal,
            B.BeginningBalance AS Act_End_Bal,
            A.UnpostedBatchAmount AS Unpst_Btchs,
            B.BeginningBalance - A.EndingGLBalance AS Variance
    FROM    RInvAccountSummary A 
    INNER JOIN RInvAccountSummary B  ON ( A.CompanyNumber = B.CompanyNumber AND A.LongAccount = B.LongAccount )
	inner join dbo.RInvAccountList ial on a.companynumber = ial.companynumber and a.longaccount = ial.longaccount
    Inner Join RCompanies c On (A.CompanyNumber = C.CompanyNumber) 
    WHERE   A.LongAccount NOT IN ( ''GL Class Not in Base Table'', ''Outside Operations'', ''Future GL'' ) AND
            A.GLRollOK = ''No'' AND
            DATEDIFF(Day, A.PeriodEnds, B.PeriodEnds) BETWEEN 1 And 50


' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Report4_GL_Roll_Forward] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Report6_Out_of_Balance]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Report6_Out_of_Balance]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Report6_Out_of_Balance]
AS  SELECT 
            A.PeriodEnds,
            A.CompanyNumber AS Company,
			ial.BusinessUnit,
            A.LongAccount,
            SUM(A.EndingGLBalance) AS EndingGL,
            SUM(A.AmountOnHand) AS EndingPerpetual,
            SUM(A.EndingGLBalance) - SUM(A.AmountOnHand) + Sum(A.BalCXVar) AS OutofBalance
    FROM    dbo.RInvAccountSummary A 
    Inner Join RCompanies c On (A.CompanyNumber = C.CompanyNumber) 
    INNER JOIN dbo.RConstants
            ON ( 1 = 1 ) 
    INNER JOIN dbo.RInvAccountSummary B
            ON ( A.CompanyNumber = B.CompanyNumber AND
                 A.LongAccount = B.LongAccount )
		inner join dbo.RInvAccountList ial
					on a.companynumber = ial.companynumber
					and a.longaccount = ial.longaccount
    WHERE   B.GLRollOK LIKE ''End%''
    GROUP BY A.CompanyNumber,
			ial.BusinessUnit,
            A.LongAccount,
            A.PeriodEnds,
            Threshold1,
            B.PeriodEnds
    HAVING  ABS(SUM(A.EndingGLBalance) - SUM(A.AmountOnHand)) > Threshold1
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Report6_Out_of_Balance] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Report7_Manual_JE]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Report7_Manual_JE]'))
EXEC dbo.sp_executesql @statement = N'

CREATE  VIEW [dbo].[v_Report7_Manual_JE]
AS
SELECT 
            GLCO AS Company,
            PeriodEnds,
            GLDCT AS ''DocType'',
            GLDOC AS ''DocNumber'',
            GLANI AS Account,
            SUM(GLAA) AS Amount,
            GLUSER AS ''USER''
    FROM    F0911
    Inner Join RCompanies c On (GLCO = C.CompanyNumber) 
    WHERE   GLDCT LIKE ''J%'' AND GLDCTO = '''' AND GLICUT In (''G'',''D'')
    GROUP BY GLCO,
            GLANI,
            PeriodEnds,
            GLDCT,
            GLDOC,
            GLUSER
    HAVING  SUM(GLAA) <> 0

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Report7_Manual_JE] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Report8_FutureGL]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Report8_FutureGL]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Report8_FutureGL]
AS  SELECT TOP 100 PERCENT
            GLCO AS Company,
            GLANI AS Account,
            PeriodEnds,
            GLDCT AS [Doc Type],
            GLDOC AS [Doc Number],
            GLICU AS [Batch Number],
            GLICUT AS [Batch Type],
            SUM(GLAA) AS Amount
    FROM    dbo.F0911
    Inner Join RCompanies c On (GLCO = C.CompanyNumber) 
    WHERE   GLANI = ''Future GL''
    GROUP BY GLCO,
            GLANI,
            PeriodEnds,
            GLDCT,
            GLDOC,
            GLICU,
            GLICUT
    ORDER BY GLCO,
            GLANI,
            PeriodEnds,
            GLDCT,
            GLDOC

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Report8_FutureGL] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_RIntercoTypes]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_RIntercoTypes]'))
EXEC dbo.sp_executesql @statement = N'CREATE View [dbo].[v_RIntercoTypes] As

	Select Distinct SDOCTO As OrigOrderType, SDDCTO As OrderType, SDRCTO As POType
	From F4211 With (NOLOCK)
	Where SDKCOO <> SDOKCO And SDOORN > 0 And SDRORN > 0 And SDDCTO <> ''SQ'' And SDOKCO <> ''''
	
	Union

	Select Distinct SDOCTO As OrigOrderType, SDDCTO As OrderType, SDRCTO As POType
	From			F42119 With (NOLOCK)
	Where			SDOORN > 0 And SDRORN > 0 And SDKCOO <> SDOKCO And SDDCTO <> ''SQ'' And SDOKCO <> ''''' 
GO
ALTER AUTHORIZATION ON [dbo].[v_RIntercoTypes] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_RInvoiceTypes]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_RInvoiceTypes]'))
EXEC dbo.sp_executesql @statement = N'Create View [dbo].[v_RInvoiceTypes] As
SELECT DISTINCT 	SDDCT As DocType
FROM 				dbo.F42119 With (NOLOCK)
WHERE				SDDOC > 0

Union

SELECT DISTINCT 	GLDCT As DocType
FROM 				dbo.F0911 With (NOLOCK)
WHERE 				GLICUT IN(''IB'',''I'',''ST'') AND GLDCT NOT IN('''',''JE'')' 
GO
ALTER AUTHORIZATION ON [dbo].[v_RInvoiceTypes] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Summarized_Cardex]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Summarized_Cardex]'))
EXEC dbo.sp_executesql @statement = N'





CREATE      VIEW [dbo].[v_Summarized_Cardex]
AS
SELECT     	PeriodEnds, ILKCO, InventoryAccount, ILMCU, ILITM, ILLOCN, ILLOTN, SUM(ILPAID) AS Amount, Sum(ILTRQT) As Quantity
FROM        dbo.F4111B
GROUP BY 	PeriodEnds, ILKCO, InventoryAccount, ILMCU, ILITM, ILITM, ILLOCN, ILLOTN 







' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Summarized_Cardex] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Unbalanced_Stock_Transfers]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Unbalanced_Stock_Transfers]'))
EXEC dbo.sp_executesql @statement = N'create view [dbo].[v_Unbalanced_Stock_Transfers] As
Select	ILDCT As DocType, 
		ILDOC As DocNumber
From	F4111B
Where	ILDCT = ''IT''
Group By	ILDCT, ILDOC
Having		Sum(ILTRQT) <> 0



' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Unbalanced_Stock_Transfers] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Unposted_Cardex_Net_WO]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Unposted_Cardex_Net_WO]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Unposted_Cardex_Net_WO]
AS  SELECT  CompanyNumber,
            LongAccount,
            PeriodEnds,
            DocNumber,
            OrderType
    FROM    RUnpostedCardex 
    WHERE   Status > ''90''
    GROUP BY CompanyNumber,
            LongAccount,
            PeriodEnds,
            DocNumber,
            OrderType
    HAVING  ABS(SUM(TransactionAmount)) <= .05
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Unposted_Cardex_Net_WO] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Unused_Accounts]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Unused_Accounts]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[v_Unused_Accounts]
AS  SELECT  LongAccount
    FROM    RInvAccountSummary
    GROUP BY LongAccount
    HAVING  SUM(PeriodGL) = 0 AND
            SUM(UnpostedBatchAmount) = 0 AND
            SUM(AmountonHand) = 0 AND
            SUM(AccountVariance) = 0 AND
            SUM(TransactionVariance) = 0 AND
            SUM(JournalEntries) = 0 AND
            SUM(OutOfBalance) = 0 AND
            SUM(BalCXVar) = 0

' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Unused_Accounts] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[v_Zero_Balance_Adjustments]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[v_Zero_Balance_Adjustments]'))
EXEC dbo.sp_executesql @statement = N'CREATE View [dbo].[v_Zero_Balance_Adjustments] As
Select	ILKCO As CompanyNumber,
		InventoryAccount,
		PeriodEnds,
		ILDCT As DocType,
		ILDOC As DocNumber,
		ILDCTO As OrderType,
		Cast(Sum(ILPAID) as Decimal(18,2)) As Amount
From	F4111B
Where	ILTREX = ''Zero Balance Adjustment       ''
Group By	ILKCO, InventoryAccount, PeriodEnds, ILDCT, ILDOC, ILDCTO
Having		Abs(Sum(ILPAID)) > 1
' 
GO
ALTER AUTHORIZATION ON [dbo].[v_Zero_Balance_Adjustments] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vcr_F0008]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vcr_F0008]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vcr_F0008]
AS
SELECT     FiscalDatePattern AS CDDTPN, FiscalYear AS CDFY, DateFiscalYearBegins AS CDDFYJ, EndOfPeriod01 AS CDD01J, EndOfPeriod02 AS CDD02J, 
                      EndOfPeriod03 AS CDD03J, EndOfPeriod04 AS CDD04J, EndOfPeriod05 AS CDD05J, EndOfPeriod06 AS CDD06J, EndOfPeriod07 AS CDD07J, 
                      EndOfPeriod08 AS CDD08J, EndOfPeriod09 AS CDD09J, EndOfPeriod10 AS CDD10J, EndOfPeriod11 AS CDD11J, EndOfPeriod12 AS CDD12J, 
                      EndOfPeriod13 AS CDD13J, EndOfPeriod14 AS CDD14J
FROM         FB91DWCR2.dbo.JDEGSAccountFiscalDatePatterns
WHERE DateFiscalYearBegins >= ''1/1/2000''

' 
GO
ALTER AUTHORIZATION ON [dbo].[vcr_F0008] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vcr_F0011]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vcr_F0011]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vcr_F0011]
AS
SELECT     BatchType AS ICICUT, BatchNumber AS ICICU, UserID AS ICUSER, BatchApprovedforPosting AS ICIAPP, BatchDate AS ICDICJ, 
                      BalancedDocumentsandAmounts AS ICBAL, BatchStatus AS ICIST
FROM         FB91DWCR2.dbo.JDEGSBatchControlRecords
Where BatchType IN (''0'', ''O'', ''S'', ''ST'', ''IB'', ''T'', ''N'', ''NC'', ''G'') And BatchDate >= ''2010-07-01 00:00:00''


' 
GO
ALTER AUTHORIZATION ON [dbo].[vcr_F0011] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vcr_F4095]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vcr_F4095]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vcr_F4095] AS
SELECT    CompanyNumber AS MLCO, 
	NumberAAITableNumber AS MLANUM, 
	OrderTypeCode AS MLDCTO, 
	DocumentType AS MLDCT, 
	GLCategory AS MLGLPT, 
     Case When BusinessUnitCode Is Null Then '''' Else RTRIM(BusinessUnitCode) End AS MLMCU, 
	ObjectAccount AS MLOBJ, 
	Case when Subsidiary Is Null Then '''' Else Subsidiary End AS MLSUB, 
	CostType AS MLCOST
FROM      FB91DWCR2.dbo.JDEIBDistributionMFGAAIValue
WHERE    NumberAAITableNumber BETWEEN 3100 and 4399
' 
GO
ALTER AUTHORIZATION ON [dbo].[vcr_F4095] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vcr_F41001]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vcr_F41001]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vcr_F41001]
AS
SELECT     BusinessUnitCode AS CIMCU, AddressNumber AS CIAN8
FROM        FB91DWCR2.dbo.JDEINBranchPlantConstants
WHERE BusinessUnitCode <> '''' 
' 
GO
ALTER AUTHORIZATION ON [dbo].[vcr_F41001] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vcr_F4102]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vcr_F4102]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vcr_F4102]
AS
SELECT     A.BusinessUnitCode AS IBMCU, ItemNumber AS IBITM, ItemNumber02 AS IBLITM, GLCategory AS IBGLPT, StockingTypeCode AS IBSTKT, 
                      A.DateUpdated AS IBUPMJ, SalesCategory01Code AS IBSRP1, SalesCategory02Code AS IBSRP2, SalesCategory03Code AS IBSRP3, 
                      SalesCategory04Code AS IBSRP4, SalesCategory05Code AS IBSRP5, SalesCategory06Code AS IBSRP6, SalesCategory07Code AS IBSRP7, 
                      SalesCategory08Code AS IBSRP8, SalesCategory09Code AS IBSRP9, SalesCategory10Code AS IBSRP0, PurchasingCategory01Code AS IBPRP1, 
                      PurchasingCategory02Code AS IBPRP2, PurchasingCategory03Code AS IBPRP3, PurchasingCategory04Code AS IBPRP4, 
                      PurchasingCategory05Code AS IBPRP5, PurchasingCategory06Code AS IBPRP6, PurchasingCategory07Code AS IBPRP7, 
                      PurchasingCategory08Code AS IBPRP8, PurchasingCategory09Code AS IBPRP9, PurchasingCategory10Code AS IBPRP0
FROM          FB91DWCR2.dbo.JDEINItemBranch A

' 
GO
ALTER AUTHORIZATION ON [dbo].[vcr_F4102] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vcr_F4108]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vcr_F4108]'))
EXEC dbo.sp_executesql @statement = N'

CREATE View [dbo].[vcr_F4108]
AS
Select LotNumber as IOLOTN, BusinessUnitCode as	IOMCU, ItemNumber as IOITM, LotExpirationDate as IOMMEJ 
from  FB91DWCR2.dbo.JDEINLotMaster
' 
GO
ALTER AUTHORIZATION ON [dbo].[vcr_F4108] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F0010]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F0010]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vt_F0010]
AS
SELECT     CompanyNumber AS CCCO, CompanyName AS CCNAME, FiscalDatePattern AS CCDTPN, DateFiscalYearBegins AS CCDFYJ, 
                      CurrentPeriod AS CCPNC
FROM        FB91DWCR2.dbo.JDEGSCompanyMaster

' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F0010] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F0902]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F0902]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vt_F0902]
AS

SELECT			AccountID AS GBAID, FiscalYear AS GBFY, LedgerTypeCode AS GBLT, CompanyNumber AS GBCO, SUM(PriorYearCloseBalance) AS GBAPYC, 
                      SUM(NetPosting01) AS GBAN01, SUM(NetPosting02) AS GBAN02, SUM(NetPosting03) AS GBAN03, SUM(NetPosting04) AS GBAN04, SUM(NetPosting05) AS GBAN05, 
                      SUM(NetPosting06) AS GBAN06, SUM(NetPosting07) AS GBAN07, SUM(NetPosting08) AS GBAN08, SUM(NetPosting09) AS GBAN09, SUM(NetPosting10) AS GBAN10, 
                      SUM(NetPosting11) AS GBAN11, SUM(NetPosting12) AS GBAN12, SUM(NetPosting13) AS GBAN13, SUM(NetPosting14) AS GBAN14
FROM			FB91DWCR2.dbo.JDEGAAccountBalances
WHERE			LedgerTypeCode = ''AA'' AND Century = 20 AND FiscalYear > 8
GROUP BY		AccountID,FiscalYear,LedgerTypeCode,CompanyNumber 



' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F0902] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F0911]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F0911]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vt_F0911] 
AS

SELECT     DocumentCompany AS GLKCO, CompanyNumber AS GLCO, DocumentType AS GLDCT, DocumentNumber AS GLDOC, OrderTypeCode AS GLDCTO, 
                      PurchaseOrderDocumentType AS GLPDCT, FiscalYear AS GLFY, GLPeriodNumber AS GLPN, GLPostedCode AS GLPOST, BatchNumber AS GLICU, 
                      BatchType AS GLICUT, AccountID AS GLAID, BusinessUnitCode AS GLMCU, Object AS GLOBJ, Subsidiary AS GLSUB, GLDate AS GLDGJ, 
                      Amount AS GLAA, UserID AS GLUSER, SubLedger AS GLSBL, AccountNumber AS GLANI, cast ((0) as datetime) PeriodEnds, PONumber AS GLPO, 
                      LineNumber AS GLLNID, Ref1JEVouchInvEtc AS GLR1, Ref2AddressNumber AS GLR2, 0 AS Formatted, 0 AS Prepped, 0 AS Keyed, BatchDate, 
                      GLDate AS GLKey
FROM         FB91DWCR2.dbo.JDEGAAccountLedger A, (SELECT DISTINCT ObjectAccount FROM FB91DWCR2.dbo.JDEIBDistributionMFGAAIValue Inner Join RConstants On (NumberAAITableNumber = AAITableNum And DocumentType = AAIDocType)) AS T 
WHERE		A.Object = T.ObjectAccount AND 	A.LedgerTypeCode = ''AA'' AND	A.GLDate >=(Select CopyFromDate From RIndexDates) AND GLDate >= (Select TransDate From RIndexDates)
' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F0911] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F3106]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F3106]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vt_F3106]
AS
SELECT     OrderNumber AS SDDOCO, DocumentNumber AS SDDOC, DocumentType AS SDDCT, GLDate AS SDDGJ, BatchNumber AS SDICU, 
                      BatchType AS SDICUT, BatchDate AS SDDICJ, WorkStationId As SDJOBN
FROM         FB91DWCR2.dbo.JDESFWOCrossReferenceFile


' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F3106] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F3112]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F3112]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vt_F3112]
AS

SELECT     OrderNumber AS WLDOCO, OrderTypeCode AS WLDCTO, Branch AS WLMMCU, PrimaryLastSupplierNumber AS WLVEND, 
           RelatedOrderKeyCompany AS WLRKCO, RelatedPoSoWoNumber AS WLRORN, RelatedPoSoWoType AS WLRCTO, 
           RelatedPOSOLineNumber AS WLRLLN, DateUpdated AS WLUPMJ, ItemNumber2ndKit AS WLKITL, OperationsSequenceNumber AS WLOPSQ, 0 AS Formatted
FROM       FB91DWCR2.dbo.JDESFControlRoutingInstruct
WHERE	   PrimaryLastSupplierNumber > 0
' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F3112] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F41021]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F41021]'))
EXEC dbo.sp_executesql @statement = N'





/********************* Views **********************************/

CREATE VIEW [dbo].[vt_F41021]
AS
SELECT            ItemNumber AS LIITM, A.BusinessUnitCode AS LIMCU, Location AS LILCON, LotNumber AS LILOTN, PrimaryLocation AS LIPBIN, GLCategory AS LIGLPT, 
                      LotStatusCode AS LILOTS, LastReceiptDate AS LILRCJ, QuantityOnHand AS LIPQOH, DateUpdated AS LIUPMJ, TimeOfDay AS LITDAY, 
                      A.DateUpdated + TimeOfDay / 1000000 AS LIKEY
FROM        FB91DWCR2.dbo.JDEINItemLocation A
Where		ItemNumber > 0


' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F41021] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F4105]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F4105]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vt_F4105] AS

SELECT   DISTINCT    ItemNumber AS COITM, BusinessUnitCode AS COMCU, Location AS COLOCN, LotNumber AS COLOTN, CostMethodCode AS COLEDG, 
                    UnitCost AS COUNCS, 0 AS COUPMJ, 0 AS Formatted
FROM        FB91DWCR2.dbo.JDEINCostLedger
WHERE        InventoryCostingSelection = ''I''
' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F4105] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F4111B]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F4111B]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vt_F4111B]
AS

SELECT     OrderNumberDocumentCompany AS ILKCOO, DocumentCompany AS ILKCO, DocumentType AS ILDCT, DocumentNumber AS ILDOC, 
           OrderTypeCode AS ILDCTO, BusinessUnitCode AS ILMCU, ItemNumber02 AS ILLITM, Location AS ILLOCN, LotNumber AS ILLOTN, 
           GLCategory AS ILGLPT, GLDate AS ILDGL, 
	 Case When TransactionDate = 0 Then Creationdate Else TransactionDate End AS ILTRDJ, 
	 ExtendedCostPrice AS ILPAID, BatchNumber AS ILICU, 0 AS InsertedInCXGL, 
           cast ((0) as datetime) PeriodEnds, '''' AS InventoryAccount, OrderNumber AS ILDOCO, LineNumber AS ILLNID, CreationDate AS ILCRDJ, TimeOfDay AS ILTDAY,
           AsOfPostedCode AS ILIPCD, 0 AS Repaired, TransactionReference AS ILTREF, UniqueKeyIDInternal AS ILUKID, '''' AS RCode, '''' AS OldGLClass, 
           0 AS Formatted, 0 AS RepFlag, 0 AS Prepped, CreationDate + TimeOfDay / 1000000 AS CXKey, Explanation AS ILTREX, UnitCost AS ILUNCS, 
           TransactionUOM, TransactionQuantity AS ILTRQT, '''' AS PrimeFlag, ItemNumber AS ILITM
FROM       FB91DWCR2.dbo.JDEINItemLedger A
WHERE    (AsOfPostedCode In (''S'', ''Y'','''') AND GLDate>=(Select CopyFromDate From RIndexDates) AND GLDate >= (Select TransDate From RIndexDates))        
OR (AsOfPostedCode In (''S'', ''Y'','''') AND GLDate = ''1901-01-01 00:00:00.000'' AND TransactionDate >= (Select CopyFromDate From RIndexDates))

' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F4111B] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F4111B_Batch]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F4111B_Batch]'))
EXEC dbo.sp_executesql @statement = N'


CREATE VIEW [dbo].[vt_F4111B_Batch]
AS

SELECT     OrderNumberDocumentCompany AS ILKCOO, DocumentCompany AS ILKCO, DocumentType AS ILDCT, DocumentNumber AS ILDOC, 
           OrderTypeCode AS ILDCTO, BusinessUnitCode AS ILMCU, ItemNumber02 AS ILLITM, Location AS ILLOCN, LotNumber AS ILLOTN, 
           GLCategory AS ILGLPT, GLDate AS ILDGL, 
			Case When TransactionDate = 0 Then Creationdate Else TransactionDate End AS ILTRDJ, 
			ExtendedCostPrice AS ILPAID, BatchNumber AS ILICU, 0 AS InsertedInCXGL, 
           cast ((0) as datetime) PeriodEnds, '''' AS InventoryAccount, OrderNumber AS ILDOCO, LineNumber AS ILLNID, CreationDate AS ILCRDJ, TimeOfDay AS ILTDAY,
           AsOfPostedCode AS ILIPCD, 0 AS Repaired, TransactionReference AS ILTREF, UniqueKeyIDInternal AS ILUKID, '''' AS RCode, '''' AS OldGLClass, 
           0 AS Formatted, 0 AS RepFlag, 0 AS Prepped, CreationDate + TimeOfDay / 1000000 AS CXKey, Explanation AS ILTREX, UnitCost AS ILUNCS, 
           TransactionUOM, TransactionQuantity AS ILTRQT, '''' AS PrimeFlag, ItemNumber AS ILITM
FROM       FB91DWCR2.dbo.JDEINItemLedger A
WHERE    (AsOfPostedCode In (''Y'', ''S'','' '') AND GLDate>=(Select CopyFromDate From RIndexDates) AND GLDate >= (Select TransDate From RIndexDates))

' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F4111B_Batch] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F4111B_NoBatch]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F4111B_NoBatch]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vt_F4111B_NoBatch]
AS

SELECT     OrderNumberDocumentCompany AS ILKCOO, DocumentCompany AS ILKCO, DocumentType AS ILDCT, DocumentNumber AS ILDOC, 
           OrderTypeCode AS ILDCTO, BusinessUnitCode AS ILMCU, ItemNumber02 AS ILLITM, Location AS ILLOCN, LotNumber AS ILLOTN, 
           GLCategory AS ILGLPT, GLDate AS ILDGL, 
			Case When TransactionDate = 0 Then Creationdate Else TransactionDate End AS ILTRDJ, 
			ExtendedCostPrice AS ILPAID, BatchNumber AS ILICU, 0 AS InsertedInCXGL, 
           cast ((0) as datetime) PeriodEnds, '''' AS InventoryAccount, OrderNumber AS ILDOCO, LineNumber AS ILLNID, CreationDate AS ILCRDJ, TimeOfDay AS ILTDAY,
           AsOfPostedCode AS ILIPCD, 0 AS Repaired, TransactionReference AS ILTREF, UniqueKeyIDInternal AS ILUKID, '''' AS RCode, '''' AS OldGLClass, 
           0 AS Formatted, 0 AS RepFlag, 0 AS Prepped, CreationDate + TimeOfDay / 1000000 AS CXKey, Explanation AS ILTREX, UnitCost AS ILUNCS, 
           TransactionUOM, TransactionQuantity AS ILTRQT, '''' AS PrimeFlag, ItemNumber AS ILITM
FROM       FB91DWCR2.dbo.JDEINItemLedger A
WHERE    (AsOfPostedCode In (''Y'', ''S'','' '') AND GLDate <= ''1901-01-01 00:00:00.000'' AND TransactionDate >= (Select CopyFromDate From RIndexDates))

' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F4111B_NoBatch] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F4211]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F4211]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vt_F4211]
AS
SELECT        OrderNumberDocumentCompany AS SDKCOO, OrderNumber AS SDDOCO, OrderTypeCode AS SDDCTO, LineNumber AS SDLNID, 
                      ItemNumber02 AS SDLITM, UnitCost AS SDUNCS, ExtendedCost AS SDECST, TransferCost AS SDTCST, UnitPrice AS SDUPRC, 
                      DocumentNumber AS SDDOC, DocumentType AS SDDCT, BusinessUnitCode AS SDMCU, CompanyNumber AS SDCO, GLDate AS SDDGL, 
                      GLOffset AS SDGLC, LineType AS SDLNTY, cast ((0) as datetime) PeriodEnds, CostOverrideCode AS SDCSTO, SalesOrderStatus01 AS SDSO01, 
                      SalesOrderStatus02 AS SDSO02, Location AS SDLOCN, LotNumber AS SDLOTN, RelatedPoSoWoNumber AS SDRORN, 
                      RelatedPoSoWoType AS SDRCTO, RelatedPOSOLineNumber AS SDRLLN, TransactionDate AS SDTRDJ, PrimaryQuantityOrdered AS SDPQOR, 
                      AddressNumber AS SDAN8, ShipToNumber AS SDSHAN, 0 AS Formatted, StatusCodeLast AS SDLTTR, StatusCodeNext AS SDNXTR, 
                      UnitOfMeasurePrimary AS SDUOM1, ExtendedPrice AS SDAEXP, QuantityShipped AS SDSOQS, UnitOfMeasureAsInput AS SDUOM, 
                      QuantityBackordered AS SDSOBK, OriginalDocumentCompany AS SDOKC, OriginalDocumentNumber AS SDODOC, 
                      OriginalDocumentTypeCode AS SDODCT, OriginalOrderNumber AS SDOORN, OriginalOrderTypeCode AS SDOCTO, 
                      OriginalOrderDocumentCompany AS SDOKCO, OriginalLineNumber AS SDOGNO, RelatedOrderKeyCompany AS SDRKCO
FROM        FB91DWCR2.dbo.JDESOSalesOrderDetail 
WHERE		SalesOrderStatus02 = '' '' And TransactionDate >=(Select CopyFromDate From RIndexDates)

' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F4211] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F4211_F42119]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F4211_F42119]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View [dbo].[vt_F4211_F42119]    Script Date: 03/04/2011 14:29:35 ******/

CREATE VIEW [dbo].[vt_F4211_F42119]
AS
SELECT     OrderNumberDocumentCompany AS SDKCOO, OrderNumber AS SDDOCO, OrderTypeCode AS SDDCTO, LineNumber AS SDLNID, 
           ItemNumber02 AS SDLITM, UnitCost AS SDUNCS, ExtendedCost AS SDECST, TransferCost AS SDTCST, DocumentNumber AS SDDOC, 
           DocumentType AS SDDCT, BusinessUnitCode AS SDMCU, CompanyNumber AS SDCO, GLDate AS SDDGL, GLOffset AS SDGLC, LineType AS SDLNTY, 
           cast((0)as datetime) PeriodEnds, CostOverrideCode AS SDCSTO, SalesOrderStatus01 AS SDSO01, SalesOrderStatus02 AS SDSO02, Location AS SDLOCN, 
           LotNumber AS SDLOTN, RelatedPoSoWoNumber AS SDRORN, RelatedPoSoWoType AS SDRCTO, RelatedPOSOLineNumber AS SDRLLN, 
           PrimaryQuantityOrdered AS SDPQOR, UnitPrice AS SDUPRC, AddressNumber AS SDAN8, ShipToNumber AS SDSHAN, 0 AS Formatted, 
           0 AS SDUPMJ, 0 AS SDTDAY, 0 AS SDKEY, StatusCodeNext AS SDNXTR, StatusCodeLast AS SDLTTR, 
           UnitOfMeasurePrimary AS SDUOM1, ExtendedPrice AS SDAEXP, QuantityShipped AS SDSOQS, 
           UnitOfMeasureAsInput AS SDUOM, QuantityBackordered AS SDSOBK, OriginalDocumentCompany AS SDOKC, OriginalDocumentNumber AS SDODOC, 
           OriginalDocumentTypeCode AS SDODCT, OriginalOrderNumber AS SDOORN, OriginalOrderTypeCode AS SDOCTO, 
           OriginalOrderDocumentCompany AS SDOKCO, OriginalLineNumber AS SDOGNO, RelatedOrderKeyCompany AS SDRKCO
FROM       FB91DWCR2.dbo.JDESOSalesOrderDetail A
WHERE     SalesOrderStatus02 <> '' ''

' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F4211_F42119] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F42119]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F42119]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vt_F42119]
AS

SELECT				  OrderNumberDocumentCompany AS SDKCOO, OrderNumber AS SDDOCO, OrderTypeCode AS SDDCTO, LineNumber AS SDLNID, 
                      ItemNumber02 AS SDLITM, UnitCost AS SDUNCS, ExtendedCost AS SDECST, TransferCost AS SDTCST, DocumentNumber AS SDDOC, 
                      DocumentType AS SDDCT, BusinessUnitCode AS SDMCU, CompanyNumber AS SDCO, GLDate AS SDDGL, GLOffset AS SDGLC, LineType AS SDLNTY, 
                      cast ((0) as datetime) PeriodEnds, CostOverrideCode AS SDCSTO, SalesOrderStatus01 AS SDSO01, SalesOrderStatus02 AS SDSO02, Location AS SDLOCN, 
                      LotNumber AS SDLOTN, RelatedPoSoWoNumber AS SDRORN, RelatedPoSoWoType AS SDRCTO, RelatedPOSOLineNumber AS SDRLLN, 
                      PrimaryQuantityOrdered AS SDPQOR, UnitPrice AS SDUPRC, AddressNumber AS SDAN8, ShipToNumber AS SDSHAN, 0 AS Formatted, 
                      0 AS SDUPMJ, 0 AS SDTDAY, 0 AS SDKEY, StatusCodeLast AS SDNXTR, 
                      StatusCodeNext AS SDLTTR, UnitOfMeasurePrimary AS SDUOM1, ExtendedPrice AS SDAEXP, QuantityShipped AS SDSOQS, 
                      UnitOfMeasureAsInput AS SDUOM, QuantityBackordered AS SDSOBK, OriginalDocumentCompany AS SDOKC, OriginalDocumentNumber AS SDODOC, 
                      OriginalDocumentTypeCode AS SDODCT, OriginalOrderNumber AS SDOORN, OriginalOrderTypeCode AS SDOCTO, 
                      OriginalOrderDocumentCompany AS SDOKCO, OriginalLineNumber AS SDOGNO, RelatedOrderKeyCompany AS SDRKCO

FROM			FB91DWCR2.dbo.JDESOSalesOrderDetailHistory A
WHERE			GLDate >= (select TransDate From RIndexDates) And Not Exists (Select * From T42119 Where OrderNumberDocumentCompany = SDKCOO And OrderNumber = SDDOCO And
				OrderTypeCode = SDDCTO And  LineNumber = SDLNID)

' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F42119] TO  SCHEMA OWNER 
GO
/****** Object:  View [dbo].[vt_F4311]    Script Date: 5/8/13 12:13:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vt_F4311]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vt_F4311]
AS

SELECT     OrderNumberDocumentCompany AS PDKCOO, OrderNumber AS PDDOCO, OrderTypeCode AS PDDCTO, OrderSuffix As PDSFXO, LineNumber AS PDLNID, 
           ItemNumber02 AS PDLITM, PurchasingUnitPrice AS PDPRRC, ExtendedPrice AS PDAEXP, BusinessUnitCode AS PDMCU, A.CompanyNumber AS PDCO, 
           GLDate AS PDDGL, GLOffset AS PDGLC, LineType AS PDLNTY, cast ((0) as datetime) PeriodEnds, Location AS PDLOCN, LotNumber AS PDLOTN, 
           RelatedPoSoWoNumber AS PDRORN, RelatedPoSoWoType AS PDRCTO, RelatedPOSOLineNumber AS PDRLLN, TransactionDate AS PDTRDJ, 
           PrimaryQuantityOrdered AS PDPQOR, AddressNumber AS PDAN8, ShipTo AS PDSHAN, AmountOpen AS PDAOPN, AmountReceived AS PDAREC, 
           0 AS Formatted, QuantityOpen AS PDUOPN, ReceivedQuantity AS PDUREC, 0 AS PDKEY, 
           StatusCodeLast AS PDLTTR, StatusCodeNext AS PDNXTR, UnitOfMeasureAsInput AS PDUOM, RelatedOrderKeyCompany AS PDRCO
FROM       FB91DWCR2.dbo.JDEPOPurchaseOrderDetail A
Where     LineType = ''D''
' 
GO
ALTER AUTHORIZATION ON [dbo].[vt_F4311] TO  SCHEMA OWNER 
GO
SET ANSI_PADDING ON

GO